• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

devonfw / IDEasy / 13771076034

10 Mar 2025 05:34PM UTC coverage: 68.473% (+0.002%) from 68.471%
13771076034

Pull #1118

github

web-flow
Merge 744098bff into fc60251b9
Pull Request #1118: isExpectedFolder(): log level now generic with default being WARNING

3043 of 4891 branches covered (62.22%)

Branch coverage included in aggregate %.

7888 of 11073 relevant lines covered (71.24%)

3.1 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

66.43
cli/src/main/java/com/devonfw/tools/ide/io/FileAccessImpl.java
1
package com.devonfw.tools.ide.io;
2

3
import java.io.BufferedOutputStream;
4
import java.io.FileInputStream;
5
import java.io.FileOutputStream;
6
import java.io.IOException;
7
import java.io.InputStream;
8
import java.io.OutputStream;
9
import java.io.Reader;
10
import java.io.Writer;
11
import java.net.URI;
12
import java.net.http.HttpClient;
13
import java.net.http.HttpClient.Redirect;
14
import java.net.http.HttpRequest;
15
import java.net.http.HttpResponse;
16
import java.nio.file.FileSystem;
17
import java.nio.file.FileSystemException;
18
import java.nio.file.FileSystems;
19
import java.nio.file.Files;
20
import java.nio.file.LinkOption;
21
import java.nio.file.NoSuchFileException;
22
import java.nio.file.Path;
23
import java.nio.file.StandardCopyOption;
24
import java.nio.file.attribute.BasicFileAttributes;
25
import java.nio.file.attribute.FileTime;
26
import java.nio.file.attribute.PosixFilePermission;
27
import java.nio.file.attribute.PosixFilePermissions;
28
import java.security.DigestInputStream;
29
import java.security.MessageDigest;
30
import java.security.NoSuchAlgorithmException;
31
import java.time.Duration;
32
import java.time.LocalDateTime;
33
import java.util.ArrayList;
34
import java.util.HashSet;
35
import java.util.Iterator;
36
import java.util.List;
37
import java.util.Map;
38
import java.util.Properties;
39
import java.util.Set;
40
import java.util.function.Consumer;
41
import java.util.function.Function;
42
import java.util.function.Predicate;
43
import java.util.stream.Stream;
44

45
import org.apache.commons.compress.archivers.ArchiveEntry;
46
import org.apache.commons.compress.archivers.ArchiveInputStream;
47
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
48
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
49

50
import com.devonfw.tools.ide.cli.CliException;
51
import com.devonfw.tools.ide.cli.CliOfflineException;
52
import com.devonfw.tools.ide.context.IdeContext;
53
import com.devonfw.tools.ide.log.IdeLogLevel;
54
import com.devonfw.tools.ide.os.SystemInfoImpl;
55
import com.devonfw.tools.ide.process.ProcessContext;
56
import com.devonfw.tools.ide.util.DateTimeUtil;
57
import com.devonfw.tools.ide.util.FilenameUtil;
58
import com.devonfw.tools.ide.util.HexUtil;
59

60
/**
61
 * Implementation of {@link FileAccess}.
62
 */
63
public class FileAccessImpl implements FileAccess {
64

65
  private static final String WINDOWS_FILE_LOCK_DOCUMENTATION_PAGE = "https://github.com/devonfw/IDEasy/blob/main/documentation/windows-file-lock.adoc";
66

67
  private static final String WINDOWS_FILE_LOCK_WARNING =
68
      "On Windows, file operations could fail due to file locks. Please ensure the files in the moved directory are not in use. For further details, see: \n"
69
          + WINDOWS_FILE_LOCK_DOCUMENTATION_PAGE;
70

71
  private static final Map<String, String> FS_ENV = Map.of("encoding", "UTF-8");
5✔
72

73
  private final IdeContext context;
74

75
  /**
76
   * The constructor.
77
   *
78
   * @param context the {@link IdeContext} to use.
79
   */
80
  public FileAccessImpl(IdeContext context) {
81

82
    super();
2✔
83
    this.context = context;
3✔
84
  }
1✔
85

86
  private HttpClient createHttpClient(String url) {
87

88
    HttpClient.Builder builder = HttpClient.newBuilder().followRedirects(Redirect.ALWAYS);
4✔
89
    return builder.build();
3✔
90
  }
91

92
  @Override
93
  public void download(String url, Path target) {
94

95
    this.context.info("Trying to download {} from {}", target.getFileName(), url);
15✔
96
    mkdirs(target.getParent());
4✔
97
    try {
98
      if (this.context.isOffline()) {
4!
99
        throw CliOfflineException.ofDownloadViaUrl(url);
×
100
      }
101
      if (url.startsWith("http")) {
4✔
102

103
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)).GET().build();
7✔
104
        HttpClient client = createHttpClient(url);
4✔
105
        HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
5✔
106
        int statusCode = response.statusCode();
3✔
107
        if (statusCode == 200) {
3!
108
          downloadFileWithProgressBar(url, target, response);
6✔
109
        } else {
110
          throw new IllegalStateException("Download failed with status code " + statusCode);
×
111
        }
112
      } else if (url.startsWith("ftp") || url.startsWith("sftp")) {
9!
113
        throw new IllegalArgumentException("Unsupported download URL: " + url);
×
114
      } else {
115
        Path source = Path.of(url);
5✔
116
        if (isFile(source)) {
4!
117
          // network drive
118

119
          copyFileWithProgressBar(source, target);
5✔
120
        } else {
121
          throw new IllegalArgumentException("Download path does not point to a downloadable file: " + url);
×
122
        }
123
      }
124
    } catch (Exception e) {
×
125
      throw new IllegalStateException("Failed to download file from URL " + url + " to " + target, e);
×
126
    }
1✔
127
  }
1✔
128

129
  /**
130
   * Downloads a file while showing a {@link IdeProgressBar}.
131
   *
132
   * @param url the url to download.
133
   * @param target Path of the target directory.
134
   * @param response the {@link HttpResponse} to use.
135
   */
136
  private void downloadFileWithProgressBar(String url, Path target, HttpResponse<InputStream> response) {
137

138
    long contentLength = response.headers().firstValueAsLong("content-length").orElse(-1);
7✔
139
    informAboutMissingContentLength(contentLength, url);
4✔
140

141
    byte[] data = new byte[1024];
3✔
142
    boolean fileComplete = false;
2✔
143
    int count;
144

145
    try (InputStream body = response.body();
4✔
146
        FileOutputStream fileOutput = new FileOutputStream(target.toFile());
6✔
147
        BufferedOutputStream bufferedOut = new BufferedOutputStream(fileOutput, data.length);
7✔
148
        IdeProgressBar pb = this.context.newProgressBarForDownload(contentLength)) {
5✔
149
      while (!fileComplete) {
2✔
150
        count = body.read(data);
4✔
151
        if (count <= 0) {
2✔
152
          fileComplete = true;
3✔
153
        } else {
154
          bufferedOut.write(data, 0, count);
5✔
155
          pb.stepBy(count);
5✔
156
        }
157
      }
158

159
    } catch (Exception e) {
×
160
      throw new RuntimeException(e);
×
161
    }
1✔
162
  }
1✔
163

164
  /**
165
   * Copies a file while displaying a progress bar.
166
   *
167
   * @param source Path of file to copy.
168
   * @param target Path of target directory.
169
   */
170
  private void copyFileWithProgressBar(Path source, Path target) throws IOException {
171

172
    try (InputStream in = new FileInputStream(source.toFile()); OutputStream out = new FileOutputStream(target.toFile())) {
12✔
173
      long size = getFileSize(source);
4✔
174
      byte[] buf = new byte[1024];
3✔
175
      try (IdeProgressBar pb = this.context.newProgressbarForCopying(size)) {
5✔
176
        int readBytes;
177
        while ((readBytes = in.read(buf)) > 0) {
6✔
178
          out.write(buf, 0, readBytes);
5✔
179
          if (size > 0) {
4!
180
            pb.stepBy(readBytes);
5✔
181
          }
182
        }
183
      } catch (Exception e) {
×
184
        throw new RuntimeException(e);
×
185
      }
1✔
186
    }
187
  }
1✔
188

189
  private void informAboutMissingContentLength(long contentLength, String url) {
190

191
    if (contentLength < 0) {
4✔
192
      this.context.warning("Content-Length was not provided by download from {}", url);
10✔
193
    }
194
  }
1✔
195

196
  @Override
197
  public void mkdirs(Path directory) {
198

199
    if (Files.isDirectory(directory)) {
5✔
200
      return;
1✔
201
    }
202
    this.context.trace("Creating directory {}", directory);
10✔
203
    try {
204
      Files.createDirectories(directory);
5✔
205
    } catch (IOException e) {
×
206
      throw new IllegalStateException("Failed to create directory " + directory, e);
×
207
    }
1✔
208
  }
1✔
209

210
  @Override
211
  public boolean isFile(Path file) {
212

213
    if (!Files.exists(file)) {
5!
214
      this.context.trace("File {} does not exist", file);
×
215
      return false;
×
216
    }
217
    if (Files.isDirectory(file)) {
5!
218
      this.context.trace("Path {} is a directory but a regular file was expected", file);
×
219
      return false;
×
220
    }
221
    return true;
2✔
222
  }
223

224
  @Override
225
  public boolean isExpectedFolder(Path folder) {
226

227
    return isExpectedFolder(folder, IdeLogLevel.WARNING);
5✔
228
  }
229

230
  @Override
231
  public boolean isExpectedFolder(Path folder, IdeLogLevel logLevel) {
232

233
    if (Files.isDirectory(folder)) {
5✔
234
      return true;
2✔
235
    }
236
    this.context.level(logLevel).log("Expected folder was not found at {}", folder);
13✔
237
    return false;
2✔
238
  }
239

240
  @Override
241
  public String checksum(Path file, String hashAlgorithm) {
242

243
    MessageDigest md;
244
    try {
245
      md = MessageDigest.getInstance(hashAlgorithm);
×
246
    } catch (NoSuchAlgorithmException e) {
×
247
      throw new IllegalStateException("No such hash algorithm " + hashAlgorithm, e);
×
248
    }
×
249
    byte[] buffer = new byte[1024];
×
250
    try (InputStream is = Files.newInputStream(file); DigestInputStream dis = new DigestInputStream(is, md)) {
×
251
      int read = 0;
×
252
      while (read >= 0) {
×
253
        read = dis.read(buffer);
×
254
      }
255
    } catch (Exception e) {
×
256
      throw new IllegalStateException("Failed to read and hash file " + file, e);
×
257
    }
×
258
    byte[] digestBytes = md.digest();
×
259
    return HexUtil.toHexString(digestBytes);
×
260
  }
261

262
  public boolean isJunction(Path path) {
263

264
    if (!SystemInfoImpl.INSTANCE.isWindows()) {
3!
265
      return false;
2✔
266
    }
267

268
    try {
269
      BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
×
270
      return attr.isOther() && attr.isDirectory();
×
271
    } catch (NoSuchFileException e) {
×
272
      return false; // file doesn't exist
×
273
    } catch (IOException e) {
×
274
      // errors in reading the attributes of the file
275
      throw new IllegalStateException("An unexpected error occurred whilst checking if the file: " + path + " is a junction", e);
×
276
    }
277
  }
278

279
  @Override
280
  public Path backup(Path fileOrFolder) {
281

282
    if ((fileOrFolder != null) && (Files.isSymbolicLink(fileOrFolder) || isJunction(fileOrFolder))) {
9!
283
      delete(fileOrFolder);
×
284
    } else if ((fileOrFolder != null) && Files.exists(fileOrFolder)) {
7!
285
      LocalDateTime now = LocalDateTime.now();
2✔
286
      String date = DateTimeUtil.formatDate(now, true);
4✔
287
      String time = DateTimeUtil.formatTime(now);
3✔
288
      String filename = fileOrFolder.getFileName().toString();
4✔
289
      Path backupPath = this.context.getIdeHome().resolve(IdeContext.FOLDER_BACKUPS).resolve(date).resolve(time + "_" + filename);
12✔
290
      backupPath = appendParentPath(backupPath, fileOrFolder.getParent(), 2);
6✔
291
      mkdirs(backupPath);
3✔
292
      Path target = backupPath.resolve(filename);
4✔
293
      this.context.info("Creating backup by moving {} to {}", fileOrFolder, target);
14✔
294
      move(fileOrFolder, target);
6✔
295
      return target;
2✔
296
    } else {
297
      this.context.trace("Backup of {} skipped as the path does not exist.", fileOrFolder);
10✔
298
    }
299
    return fileOrFolder;
2✔
300
  }
301

302
  private static Path appendParentPath(Path path, Path parent, int max) {
303

304
    if ((parent == null) || (max <= 0)) {
4!
305
      return path;
2✔
306
    }
307
    return appendParentPath(path, parent.getParent(), max - 1).resolve(parent.getFileName());
11✔
308
  }
309

310
  @Override
311
  public void move(Path source, Path targetDir, StandardCopyOption... copyOptions) {
312

313
    this.context.trace("Moving {} to {}", source, targetDir);
14✔
314
    try {
315
      Files.move(source, targetDir, copyOptions);
5✔
316
    } catch (IOException e) {
×
317
      String fileType = Files.isSymbolicLink(source) ? "symlink" : isJunction(source) ? "junction" : Files.isDirectory(source) ? "directory" : "file";
×
318
      String message = "Failed to move " + fileType + ": " + source + " to " + targetDir + ".";
×
319
      if (this.context.getSystemInfo().isWindows()) {
×
320
        message = message + "\n" + WINDOWS_FILE_LOCK_WARNING;
×
321
      }
322
      throw new IllegalStateException(message, e);
×
323
    }
1✔
324
  }
1✔
325

326
  @Override
327
  public void copy(Path source, Path target, FileCopyMode mode, PathCopyListener listener) {
328

329
    if (mode != FileCopyMode.COPY_TREE_CONTENT) {
3✔
330
      // if we want to copy the file or folder "source" to the existing folder "target" in a shell this will copy
331
      // source into that folder so that we as a result have a copy in "target/source".
332
      // With Java NIO the raw copy method will fail as we cannot copy "source" to the path of the "target" folder.
333
      // For folders we want the same behavior as the linux "cp -r" command so that the "source" folder is copied
334
      // and not only its content what also makes it consistent with the move method that also behaves this way.
335
      // Therefore we need to add the filename (foldername) of "source" to the "target" path before.
336
      // For the rare cases, where we want to copy the content of a folder (cp -r source/* target) we support
337
      // it via the COPY_TREE_CONTENT mode.
338
      Path fileName = source.getFileName();
3✔
339
      if (fileName != null) { // if filename is null, we are copying the root of a (virtual filesystem)
2✔
340
        target = target.resolve(fileName.toString());
5✔
341
      }
342
    }
343
    boolean fileOnly = mode.isFileOnly();
3✔
344
    String operation = mode.getOperation();
3✔
345
    if (mode.isExtract()) {
3✔
346
      this.context.debug("Starting to {} to {}", operation, target);
15✔
347
    } else {
348
      if (fileOnly) {
2✔
349
        this.context.debug("Starting to {} file {} to {}", operation, source, target);
19✔
350
      } else {
351
        this.context.debug("Starting to {} {} recursively to {}", operation, source, target);
18✔
352
      }
353
    }
354
    if (fileOnly && Files.isDirectory(source)) {
7!
355
      throw new IllegalStateException("Expected file but found a directory to copy at " + source);
×
356
    }
357
    if (mode.isFailIfExists()) {
3✔
358
      if (Files.exists(target)) {
5!
359
        throw new IllegalStateException("Failed to " + operation + " " + source + " to already existing target " + target);
×
360
      }
361
    } else if (mode == FileCopyMode.COPY_TREE_OVERRIDE_TREE) {
3✔
362
      delete(target);
3✔
363
    }
364
    try {
365
      copyRecursive(source, target, mode, listener);
6✔
366
    } catch (IOException e) {
×
367
      throw new IllegalStateException("Failed to " + operation + " " + source + " to " + target, e);
×
368
    }
1✔
369
  }
1✔
370

371
  private void copyRecursive(Path source, Path target, FileCopyMode mode, PathCopyListener listener) throws IOException {
372

373
    if (Files.isDirectory(source)) {
5✔
374
      mkdirs(target);
3✔
375
      try (Stream<Path> childStream = Files.list(source)) {
3✔
376
        Iterator<Path> iterator = childStream.iterator();
3✔
377
        while (iterator.hasNext()) {
3✔
378
          Path child = iterator.next();
4✔
379
          copyRecursive(child, target.resolve(child.getFileName().toString()), mode, listener);
10✔
380
        }
1✔
381
      }
382
      listener.onCopy(source, target, true);
6✔
383
    } else if (Files.exists(source)) {
5!
384
      if (mode.isOverrideFile()) {
3✔
385
        delete(target);
3✔
386
      }
387
      this.context.trace("Starting to {} {} to {}", mode.getOperation(), source, target);
19✔
388
      Files.copy(source, target);
6✔
389
      listener.onCopy(source, target, false);
6✔
390
    } else {
391
      throw new IOException("Path " + source + " does not exist.");
×
392
    }
393
  }
1✔
394

395
  /**
396
   * Deletes the given {@link Path} if it is a symbolic link or a Windows junction. And throws an {@link IllegalStateException} if there is a file at the given
397
   * {@link Path} that is neither a symbolic link nor a Windows junction.
398
   *
399
   * @param path the {@link Path} to delete.
400
   * @throws IOException if the actual {@link Files#delete(Path) deletion} fails.
401
   */
402
  private void deleteLinkIfExists(Path path) throws IOException {
403

404
    boolean isJunction = isJunction(path); // since broken junctions are not detected by Files.exists()
4✔
405
    boolean isSymlink = Files.exists(path) && Files.isSymbolicLink(path);
12!
406

407
    assert !(isSymlink && isJunction);
5!
408

409
    if (isJunction || isSymlink) {
4!
410
      this.context.info("Deleting previous " + (isJunction ? "junction" : "symlink") + " at " + path);
9!
411
      Files.delete(path);
2✔
412
    }
413
  }
1✔
414

415
  /**
416
   * Adapts the given {@link Path} to be relative or absolute depending on the given {@code relative} flag. Additionally, {@link Path#toRealPath(LinkOption...)}
417
   * is applied to {@code source}.
418
   *
419
   * @param source the {@link Path} to adapt.
420
   * @param targetLink the {@link Path} used to calculate the relative path to the {@code source} if {@code relative} is set to {@code true}.
421
   * @param relative the {@code relative} flag.
422
   * @return the adapted {@link Path}.
423
   * @see FileAccessImpl#symlink(Path, Path, boolean)
424
   */
425
  private Path adaptPath(Path source, Path targetLink, boolean relative) throws IOException {
426

427
    if (source.isAbsolute()) {
3✔
428
      try {
429
        source = source.toRealPath(LinkOption.NOFOLLOW_LINKS); // to transform ../d1/../d2 to ../d2
9✔
430
      } catch (IOException e) {
×
431
        throw new IOException("Calling toRealPath() on the source (" + source + ") in method FileAccessImpl.adaptPath() failed.", e);
×
432
      }
1✔
433
      if (relative) {
2✔
434
        source = targetLink.getParent().relativize(source);
5✔
435
        // to make relative links like this work: dir/link -> dir
436
        source = (source.toString().isEmpty()) ? Path.of(".") : source;
12✔
437
      }
438
    } else { // source is relative
439
      if (relative) {
2✔
440
        // even though the source is already relative, toRealPath should be called to transform paths like
441
        // this ../d1/../d2 to ../d2
442
        source = targetLink.getParent().relativize(targetLink.resolveSibling(source).toRealPath(LinkOption.NOFOLLOW_LINKS));
14✔
443
        source = (source.toString().isEmpty()) ? Path.of(".") : source;
12✔
444
      } else { // !relative
445
        try {
446
          source = targetLink.resolveSibling(source).toRealPath(LinkOption.NOFOLLOW_LINKS);
11✔
447
        } catch (IOException e) {
×
448
          throw new IOException("Calling toRealPath() on " + targetLink + ".resolveSibling(" + source + ") in method FileAccessImpl.adaptPath() failed.", e);
×
449
        }
1✔
450
      }
451
    }
452
    return source;
2✔
453
  }
454

455
  /**
456
   * Creates a Windows junction at {@code targetLink} pointing to {@code source}.
457
   *
458
   * @param source must be another Windows junction or a directory.
459
   * @param targetLink the location of the Windows junction.
460
   */
461
  private void createWindowsJunction(Path source, Path targetLink) {
462

463
    this.context.trace("Creating a Windows junction at " + targetLink + " with " + source + " as source.");
×
464
    Path fallbackPath;
465
    if (!source.isAbsolute()) {
×
466
      this.context.warning("You are on Windows and you do not have permissions to create symbolic links. Junctions are used as an "
×
467
          + "alternative, however, these can not point to relative paths. So the source (" + source + ") is interpreted as an absolute path.");
468
      try {
469
        fallbackPath = targetLink.resolveSibling(source).toRealPath(LinkOption.NOFOLLOW_LINKS);
×
470
      } catch (IOException e) {
×
471
        throw new IllegalStateException(
×
472
            "Since Windows junctions are used, the source must be an absolute path. The transformation of the passed " + "source (" + source
473
                + ") to an absolute path failed.", e);
474
      }
×
475

476
    } else {
477
      fallbackPath = source;
×
478
    }
479
    if (!Files.isDirectory(fallbackPath)) { // if source is a junction. This returns true as well.
×
480
      throw new IllegalStateException(
×
481
          "These junctions can only point to directories or other junctions. Please make sure that the source (" + fallbackPath + ") is one of these.");
482
    }
483
    this.context.newProcess().executable("cmd").addArgs("/c", "mklink", "/d", "/j", targetLink.toString(), fallbackPath.toString()).run();
×
484
  }
×
485

486
  @Override
487
  public void symlink(Path source, Path targetLink, boolean relative) {
488

489
    Path adaptedSource = null;
2✔
490
    try {
491
      adaptedSource = adaptPath(source, targetLink, relative);
6✔
492
    } catch (IOException e) {
×
493
      throw new IllegalStateException("Failed to adapt source for source (" + source + ") target (" + targetLink + ") and relative (" + relative + ")", e);
×
494
    }
1✔
495
    this.context.debug("Creating {} symbolic link {} pointing to {}", adaptedSource.isAbsolute() ? "" : "relative", targetLink, adaptedSource);
23✔
496

497
    try {
498
      deleteLinkIfExists(targetLink);
3✔
499
    } catch (IOException e) {
×
500
      throw new IllegalStateException("Failed to delete previous symlink or Windows junction at " + targetLink, e);
×
501
    }
1✔
502

503
    try {
504
      Files.createSymbolicLink(targetLink, adaptedSource);
6✔
505
    } catch (FileSystemException e) {
×
506
      if (SystemInfoImpl.INSTANCE.isWindows()) {
×
507
        this.context.info("Due to lack of permissions, Microsoft's mklink with junction had to be used to create "
×
508
            + "a Symlink. See https://github.com/devonfw/IDEasy/blob/main/documentation/symlinks.asciidoc for " + "further details. Error was: "
509
            + e.getMessage());
×
510
        createWindowsJunction(adaptedSource, targetLink);
×
511
      } else {
512
        throw new RuntimeException(e);
×
513
      }
514
    } catch (IOException e) {
×
515
      throw new IllegalStateException(
×
516
          "Failed to create a " + (adaptedSource.isAbsolute() ? "" : "relative") + "symbolic link " + targetLink + " pointing to " + source, e);
×
517
    }
1✔
518
  }
1✔
519

520
  @Override
521
  public Path toRealPath(Path path) {
522

523
    try {
524
      Path realPath = path.toRealPath();
5✔
525
      if (!realPath.equals(path)) {
4✔
526
        this.context.trace("Resolved path {} to {}", path, realPath);
14✔
527
      }
528
      return realPath;
2✔
529
    } catch (IOException e) {
×
530
      throw new IllegalStateException("Failed to get real path for " + path, e);
×
531
    }
532
  }
533

534
  @Override
535
  public Path createTempDir(String name) {
536

537
    try {
538
      Path tmp = this.context.getTempPath();
4✔
539
      Path tempDir = tmp.resolve(name);
4✔
540
      int tries = 1;
2✔
541
      while (Files.exists(tempDir)) {
5!
542
        long id = System.nanoTime() & 0xFFFF;
×
543
        tempDir = tmp.resolve(name + "-" + id);
×
544
        tries++;
×
545
        if (tries > 200) {
×
546
          throw new IOException("Unable to create unique name!");
×
547
        }
548
      }
×
549
      return Files.createDirectory(tempDir);
5✔
550
    } catch (IOException e) {
×
551
      throw new IllegalStateException("Failed to create temporary directory with prefix '" + name + "'!", e);
×
552
    }
553
  }
554

555
  @Override
556
  public void extract(Path archiveFile, Path targetDir, Consumer<Path> postExtractHook, boolean extract) {
557

558
    if (Files.isDirectory(archiveFile)) {
5✔
559
      // TODO: check this case
560
      Path properInstallDir = archiveFile; // getProperInstallationSubDirOf(archiveFile, archiveFile);
2✔
561
      this.context.warning("Found directory for download at {} hence copying without extraction!", archiveFile);
10✔
562
      copy(properInstallDir, targetDir, FileCopyMode.COPY_TREE_CONTENT);
5✔
563
      postExtractHook(postExtractHook, targetDir);
4✔
564
      return;
1✔
565
    } else if (!extract) {
2!
566
      mkdirs(targetDir);
×
567
      move(archiveFile, targetDir.resolve(archiveFile.getFileName()));
×
568
      return;
×
569
    }
570
    Path tmpDir = createTempDir("extract-" + archiveFile.getFileName());
7✔
571
    this.context.trace("Trying to extract the downloaded file {} to {} and move it to {}.", archiveFile, tmpDir, targetDir);
18✔
572
    String filename = archiveFile.getFileName().toString();
4✔
573
    TarCompression tarCompression = TarCompression.of(filename);
3✔
574
    if (tarCompression != null) {
2✔
575
      extractTar(archiveFile, tmpDir, tarCompression);
6✔
576
    } else {
577
      String extension = FilenameUtil.getExtension(filename);
3✔
578
      if (extension == null) {
2!
579
        throw new IllegalStateException("Unknown archive format without extension - can not extract " + archiveFile);
×
580
      } else {
581
        this.context.trace("Determined file extension {}", extension);
10✔
582
      }
583
      switch (extension) {
8!
584
        case "zip" -> extractZip(archiveFile, tmpDir);
×
585
        case "jar" -> extractJar(archiveFile, tmpDir);
5✔
586
        case "dmg" -> extractDmg(archiveFile, tmpDir);
×
587
        case "msi" -> extractMsi(archiveFile, tmpDir);
×
588
        case "pkg" -> extractPkg(archiveFile, tmpDir);
×
589
        default -> throw new IllegalStateException("Unknown archive format " + extension + ". Can not extract " + archiveFile);
×
590
      }
591
    }
592
    Path properInstallDir = getProperInstallationSubDirOf(tmpDir, archiveFile);
5✔
593
    postExtractHook(postExtractHook, properInstallDir);
4✔
594
    move(properInstallDir, targetDir);
6✔
595
    delete(tmpDir);
3✔
596
  }
1✔
597

598
  private void postExtractHook(Consumer<Path> postExtractHook, Path properInstallDir) {
599

600
    if (postExtractHook != null) {
2✔
601
      postExtractHook.accept(properInstallDir);
3✔
602
    }
603
  }
1✔
604

605
  /**
606
   * @param path the {@link Path} to start the recursive search from.
607
   * @return the deepest subdir {@code s} of the passed path such that all directories between {@code s} and the passed path (including {@code s}) are the sole
608
   *     item in their respective directory and {@code s} is not named "bin".
609
   */
610
  private Path getProperInstallationSubDirOf(Path path, Path archiveFile) {
611

612
    try (Stream<Path> stream = Files.list(path)) {
3✔
613
      Path[] subFiles = stream.toArray(Path[]::new);
8✔
614
      if (subFiles.length == 0) {
3!
615
        throw new CliException("The downloaded package " + archiveFile + " seems to be empty as you can check in the extracted folder " + path);
×
616
      } else if (subFiles.length == 1) {
4✔
617
        String filename = subFiles[0].getFileName().toString();
6✔
618
        if (!filename.equals(IdeContext.FOLDER_BIN) && !filename.equals(IdeContext.FOLDER_CONTENTS) && !filename.endsWith(".app") && Files.isDirectory(
19!
619
            subFiles[0])) {
620
          return getProperInstallationSubDirOf(subFiles[0], archiveFile);
9✔
621
        }
622
      }
623
      return path;
4✔
624
    } catch (IOException e) {
4!
625
      throw new IllegalStateException("Failed to get sub-files of " + path);
×
626
    }
627
  }
628

629
  @Override
630
  public void extractZip(Path file, Path targetDir) {
631

632
    this.context.info("Extracting ZIP file {} to {}", file, targetDir);
14✔
633
    URI uri = URI.create("jar:" + file.toUri());
6✔
634
    try (FileSystem fs = FileSystems.newFileSystem(uri, FS_ENV)) {
4✔
635
      long size = 0;
2✔
636
      for (Path root : fs.getRootDirectories()) {
11✔
637
        size += getFileSizeRecursive(root);
6✔
638
      }
1✔
639
      try (final IdeProgressBar progressBar = this.context.newProgressbarForExtracting(size)) {
5✔
640
        for (Path root : fs.getRootDirectories()) {
11✔
641
          copy(root, targetDir, FileCopyMode.EXTRACT, (s, t, d) -> onFileCopiedFromZip(s, t, d, progressBar));
15✔
642
        }
1✔
643
      }
644
    } catch (IOException e) {
×
645
      throw new IllegalStateException("Failed to extract " + file + " to " + targetDir, e);
×
646
    }
1✔
647
  }
1✔
648

649
  @SuppressWarnings("unchecked")
650
  private void onFileCopiedFromZip(Path source, Path target, boolean directory, IdeProgressBar progressBar) {
651

652
    if (directory) {
2✔
653
      return;
1✔
654
    }
655
    if (!context.getSystemInfo().isWindows()) {
5✔
656
      try {
657
        Object attribute = Files.getAttribute(source, "zip:permissions");
6✔
658
        if (attribute instanceof Set<?> permissionSet) {
6✔
659
          Files.setPosixFilePermissions(target, (Set<PosixFilePermission>) permissionSet);
4✔
660
        }
661
      } catch (Exception e) {
×
662
        context.error(e, "Failed to transfer zip permissions for {}", target);
×
663
      }
1✔
664
    }
665
    progressBar.stepBy(getFileSize(target));
5✔
666
  }
1✔
667

668
  @Override
669
  public void extractTar(Path file, Path targetDir, TarCompression compression) {
670

671
    extractArchive(file, targetDir, in -> new TarArchiveInputStream(compression.unpack(in)));
13✔
672
  }
1✔
673

674
  @Override
675
  public void extractJar(Path file, Path targetDir) {
676

677
    extractZip(file, targetDir);
4✔
678
  }
1✔
679

680
  /**
681
   * @param permissions The integer as returned by {@link TarArchiveEntry#getMode()} that represents the file permissions of a file on a Unix file system.
682
   * @return A String representing the file permissions. E.g. "rwxrwxr-x" or "rw-rw-r--"
683
   */
684
  public static String generatePermissionString(int permissions) {
685

686
    // Ensure that only the last 9 bits are considered
687
    permissions &= 0b111111111;
4✔
688

689
    StringBuilder permissionStringBuilder = new StringBuilder("rwxrwxrwx");
5✔
690
    for (int i = 0; i < 9; i++) {
7✔
691
      int mask = 1 << i;
4✔
692
      char currentChar = ((permissions & mask) != 0) ? permissionStringBuilder.charAt(8 - i) : '-';
12✔
693
      permissionStringBuilder.setCharAt(8 - i, currentChar);
6✔
694
    }
695

696
    return permissionStringBuilder.toString();
3✔
697
  }
698

699
  private void extractArchive(Path file, Path targetDir, Function<InputStream, ArchiveInputStream<?>> unpacker) {
700

701
    this.context.info("Extracting TAR file {} to {}", file, targetDir);
14✔
702
    try (InputStream is = Files.newInputStream(file);
5✔
703
        ArchiveInputStream<?> ais = unpacker.apply(is);
5✔
704
        IdeProgressBar pb = this.context.newProgressbarForExtracting(getFileSize(file))) {
7✔
705

706
      ArchiveEntry entry = ais.getNextEntry();
3✔
707
      boolean isTar = ais instanceof TarArchiveInputStream;
3✔
708
      while (entry != null) {
2✔
709
        String permissionStr = null;
2✔
710
        if (isTar) {
2!
711
          int tarMode = ((TarArchiveEntry) entry).getMode();
4✔
712
          permissionStr = generatePermissionString(tarMode);
3✔
713
        }
714
        Path entryName = Path.of(entry.getName());
6✔
715
        Path entryPath = targetDir.resolve(entryName).toAbsolutePath();
5✔
716
        if (!entryPath.startsWith(targetDir)) {
4!
717
          throw new IOException("Preventing path traversal attack from " + entryName + " to " + entryPath);
×
718
        }
719
        if (entry.isDirectory()) {
3✔
720
          mkdirs(entryPath);
4✔
721
        } else {
722
          // ensure the file can also be created if directory entry was missing or out of order...
723
          mkdirs(entryPath.getParent());
4✔
724
          Files.copy(ais, entryPath);
6✔
725
        }
726
        if (isTar && !this.context.getSystemInfo().isWindows()) {
7!
727
          Set<PosixFilePermission> permissions = PosixFilePermissions.fromString(permissionStr);
3✔
728
          Files.setPosixFilePermissions(entryPath, permissions);
4✔
729
        }
730
        pb.stepBy(entry.getSize());
4✔
731
        entry = ais.getNextEntry();
3✔
732
      }
1✔
733
    } catch (IOException e) {
×
734
      throw new IllegalStateException("Failed to extract " + file + " to " + targetDir, e);
×
735
    }
1✔
736
  }
1✔
737

738
  @Override
739
  public void extractDmg(Path file, Path targetDir) {
740

741
    this.context.info("Extracting DMG file {} to {}", file, targetDir);
×
742
    assert this.context.getSystemInfo().isMac();
×
743

744
    Path mountPath = this.context.getIdeHome().resolve(IdeContext.FOLDER_UPDATES).resolve(IdeContext.FOLDER_VOLUME);
×
745
    mkdirs(mountPath);
×
746
    ProcessContext pc = this.context.newProcess();
×
747
    pc.executable("hdiutil");
×
748
    pc.addArgs("attach", "-quiet", "-nobrowse", "-mountpoint", mountPath, file);
×
749
    pc.run();
×
750
    Path appPath = findFirst(mountPath, p -> p.getFileName().toString().endsWith(".app"), false);
×
751
    if (appPath == null) {
×
752
      throw new IllegalStateException("Failed to unpack DMG as no MacOS *.app was found in file " + file);
×
753
    }
754

755
    copy(appPath, targetDir, FileCopyMode.COPY_TREE_OVERRIDE_TREE);
×
756
    pc.addArgs("detach", "-force", mountPath);
×
757
    pc.run();
×
758
  }
×
759

760
  @Override
761
  public void extractMsi(Path file, Path targetDir) {
762

763
    this.context.info("Extracting MSI file {} to {}", file, targetDir);
×
764
    this.context.newProcess().executable("msiexec").addArgs("/a", file, "/qn", "TARGETDIR=" + targetDir).run();
×
765
    // msiexec also creates a copy of the MSI
766
    Path msiCopy = targetDir.resolve(file.getFileName());
×
767
    delete(msiCopy);
×
768
  }
×
769

770
  @Override
771
  public void extractPkg(Path file, Path targetDir) {
772

773
    this.context.info("Extracting PKG file {} to {}", file, targetDir);
×
774
    Path tmpDirPkg = createTempDir("ide-pkg-");
×
775
    ProcessContext pc = this.context.newProcess();
×
776
    // we might also be able to use cpio from commons-compression instead of external xar...
777
    pc.executable("xar").addArgs("-C", tmpDirPkg, "-xf", file).run();
×
778
    Path contentPath = findFirst(tmpDirPkg, p -> p.getFileName().toString().equals("Payload"), true);
×
779
    extractTar(contentPath, targetDir, TarCompression.GZ);
×
780
    delete(tmpDirPkg);
×
781
  }
×
782

783
  @Override
784
  public void delete(Path path) {
785

786
    if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
9✔
787
      this.context.trace("Deleting {} skipped as the path does not exist.", path);
10✔
788
      return;
1✔
789
    }
790
    this.context.debug("Deleting {} ...", path);
10✔
791
    try {
792
      if (Files.isSymbolicLink(path) || isJunction(path)) {
7!
793
        Files.delete(path);
×
794
      } else {
795
        deleteRecursive(path);
3✔
796
      }
797
    } catch (IOException e) {
×
798
      throw new IllegalStateException("Failed to delete " + path, e);
×
799
    }
1✔
800
  }
1✔
801

802
  private void deleteRecursive(Path path) throws IOException {
803

804
    if (Files.isDirectory(path)) {
5✔
805
      try (Stream<Path> childStream = Files.list(path)) {
3✔
806
        Iterator<Path> iterator = childStream.iterator();
3✔
807
        while (iterator.hasNext()) {
3✔
808
          Path child = iterator.next();
4✔
809
          deleteRecursive(child);
3✔
810
        }
1✔
811
      }
812
    }
813
    this.context.trace("Deleting {} ...", path);
10✔
814
    Files.delete(path);
2✔
815
  }
1✔
816

817
  @Override
818
  public Path findFirst(Path dir, Predicate<Path> filter, boolean recursive) {
819

820
    try {
821
      if (!Files.isDirectory(dir)) {
5✔
822
        return null;
2✔
823
      }
824
      return findFirstRecursive(dir, filter, recursive);
6✔
825
    } catch (IOException e) {
×
826
      throw new IllegalStateException("Failed to search for file in " + dir, e);
×
827
    }
828
  }
829

830
  private Path findFirstRecursive(Path dir, Predicate<Path> filter, boolean recursive) throws IOException {
831

832
    List<Path> folders = null;
2✔
833
    try (Stream<Path> childStream = Files.list(dir)) {
3✔
834
      Iterator<Path> iterator = childStream.iterator();
3✔
835
      while (iterator.hasNext()) {
3✔
836
        Path child = iterator.next();
4✔
837
        if (filter.test(child)) {
4✔
838
          return child;
4✔
839
        } else if (recursive && Files.isDirectory(child)) {
2!
840
          if (folders == null) {
×
841
            folders = new ArrayList<>();
×
842
          }
843
          folders.add(child);
×
844
        }
845
      }
1✔
846
    }
4!
847
    if (folders != null) {
2!
848
      for (Path child : folders) {
×
849
        Path match = findFirstRecursive(child, filter, recursive);
×
850
        if (match != null) {
×
851
          return match;
×
852
        }
853
      }
×
854
    }
855
    return null;
2✔
856
  }
857

858
  @Override
859
  public List<Path> listChildrenMapped(Path dir, Function<Path, Path> filter) {
860

861
    if (!Files.isDirectory(dir)) {
5✔
862
      return List.of();
2✔
863
    }
864
    List<Path> children = new ArrayList<>();
4✔
865
    try (Stream<Path> childStream = Files.list(dir)) {
3✔
866
      Iterator<Path> iterator = childStream.iterator();
3✔
867
      while (iterator.hasNext()) {
3✔
868
        Path child = iterator.next();
4✔
869
        Path filteredChild = filter.apply(child);
5✔
870
        if (filteredChild != null) {
2✔
871
          if (filteredChild == child) {
3!
872
            this.context.trace("Accepted file {}", child);
11✔
873
          } else {
874
            this.context.trace("Accepted file {} and mapped to {}", child, filteredChild);
×
875
          }
876
          children.add(filteredChild);
5✔
877
        } else {
878
          this.context.trace("Ignoring file {} according to filter", child);
10✔
879
        }
880
      }
1✔
881
    } catch (IOException e) {
×
882
      throw new IllegalStateException("Failed to find children of directory " + dir, e);
×
883
    }
1✔
884
    return children;
2✔
885
  }
886

887
  @Override
888
  public boolean isEmptyDir(Path dir) {
889

890
    return listChildren(dir, f -> true).isEmpty();
8✔
891
  }
892

893
  private long getFileSize(Path file) {
894

895
    try {
896
      return Files.size(file);
3✔
897
    } catch (IOException e) {
×
898
      this.context.warning(e.getMessage(), e);
×
899
      return 0;
×
900
    }
901
  }
902

903
  private long getFileSizeRecursive(Path path) {
904

905
    long size = 0;
2✔
906
    if (Files.isDirectory(path)) {
5✔
907
      try (Stream<Path> childStream = Files.list(path)) {
3✔
908
        Iterator<Path> iterator = childStream.iterator();
3✔
909
        while (iterator.hasNext()) {
3✔
910
          Path child = iterator.next();
4✔
911
          size += getFileSizeRecursive(child);
6✔
912
        }
1✔
913
      } catch (IOException e) {
×
914
        throw new RuntimeException("Failed to iterate children of folder " + path, e);
×
915
      }
1✔
916
    } else {
917
      size += getFileSize(path);
6✔
918
    }
919
    return size;
2✔
920
  }
921

922
  @Override
923
  public Path findExistingFile(String fileName, List<Path> searchDirs) {
924

925
    for (Path dir : searchDirs) {
×
926
      Path filePath = dir.resolve(fileName);
×
927
      try {
928
        if (Files.exists(filePath)) {
×
929
          return filePath;
×
930
        }
931
      } catch (Exception e) {
×
932
        throw new IllegalStateException("Unexpected error while checking existence of file " + filePath + " .", e);
×
933
      }
×
934
    }
×
935
    return null;
×
936
  }
937

938
  @Override
939
  public void makeExecutable(Path file, boolean confirm) {
940

941
    if (Files.exists(file)) {
5✔
942
      if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
943
        this.context.trace("Windows does not have executable flags hence omitting for file {}", file);
×
944
        return;
×
945
      }
946
      try {
947
        // Read the current file permissions
948
        Set<PosixFilePermission> existingPermissions = Files.getPosixFilePermissions(file);
5✔
949

950
        // Add execute permission for all users
951
        Set<PosixFilePermission> executablePermissions = new HashSet<>(existingPermissions);
5✔
952
        boolean update = false;
2✔
953
        update |= executablePermissions.add(PosixFilePermission.OWNER_EXECUTE);
6✔
954
        update |= executablePermissions.add(PosixFilePermission.GROUP_EXECUTE);
6✔
955
        update |= executablePermissions.add(PosixFilePermission.OTHERS_EXECUTE);
6✔
956

957
        if (update) {
2✔
958
          if (confirm) {
2!
959
            boolean yesContinue = this.context.question(
×
960
                "We want to execute " + file.getFileName() + " but this command seems to lack executable permissions!\n"
×
961
                    + "Most probably the tool vendor did forgot to add x-flags in the binary release package.\n"
962
                    + "Before running the command, we suggest to set executable permissions to the file:\n"
963
                    + file + "\n"
964
                    + "For security reasons we ask for your confirmation so please check this request.\n"
965
                    + "Changing permissions from " + PosixFilePermissions.toString(existingPermissions) + " to " + PosixFilePermissions.toString(
×
966
                    executablePermissions) + ".\n"
967
                    + "Do you confirm to make the command executable before running it?");
968
            if (!yesContinue) {
×
969
              return;
×
970
            }
971
          }
972
          this.context.debug("Setting executable flags for file {}", file);
10✔
973
          // Set the new permissions
974
          Files.setPosixFilePermissions(file, executablePermissions);
5✔
975
        } else {
976
          this.context.trace("Executable flags already present so no need to set them for file {}", file);
10✔
977
        }
978
      } catch (IOException e) {
×
979
        throw new RuntimeException(e);
×
980
      }
1✔
981
    } else {
982
      this.context.warning("Cannot set executable flag on file that does not exist: {}", file);
10✔
983
    }
984
  }
1✔
985

986
  @Override
987
  public void touch(Path file) {
988

989
    if (Files.exists(file)) {
5✔
990
      try {
991
        Files.setLastModifiedTime(file, FileTime.fromMillis(System.currentTimeMillis()));
5✔
992
      } catch (IOException e) {
×
993
        throw new IllegalStateException("Could not update modification-time of " + file, e);
×
994
      }
1✔
995
    } else {
996
      try {
997
        Files.createFile(file);
5✔
998
      } catch (IOException e) {
1✔
999
        throw new IllegalStateException("Could not create empty file " + file, e);
8✔
1000
      }
1✔
1001
    }
1002
  }
1✔
1003

1004
  @Override
1005
  public String readFileContent(Path file) {
1006

1007
    this.context.trace("Reading content of file from {}", file);
10✔
1008
    try {
1009
      String content = Files.readString(file);
3✔
1010
      this.context.trace("Completed reading {} character(s) from file {}", content.length(), file);
16✔
1011
      return content;
2✔
1012
    } catch (IOException e) {
×
1013
      throw new IllegalStateException("Failed to read file " + file, e);
×
1014
    }
1015
  }
1016

1017
  @Override
1018
  public void writeFileContent(String content, Path file, boolean createParentDir) {
1019

1020
    if (createParentDir) {
2!
1021
      mkdirs(file.getParent());
×
1022
    }
1023
    if (content == null) {
2!
1024
      content = "";
×
1025
    }
1026
    this.context.trace("Writing content with {} character(s) to file {}", content.length(), file);
16✔
1027
    if (Files.exists(file)) {
5✔
1028
      this.context.info("Overriding content of file {}", file);
10✔
1029
    }
1030
    try {
1031
      Files.writeString(file, content);
6✔
1032
      this.context.trace("Wrote content to file {}", file);
10✔
1033
    } catch (IOException e) {
×
1034
      throw new RuntimeException("Failed to write file " + file, e);
×
1035
    }
1✔
1036
  }
1✔
1037

1038
  @Override
1039
  public List<String> readFileLines(Path file) {
1040

1041
    this.context.trace("Reading content of file from {}", file);
10✔
1042
    if (!Files.exists(file)) {
5✔
1043
      this.context.warning("File {} does not exist", file);
10✔
1044
      return null;
2✔
1045
    }
1046
    try {
1047
      List<String> content = Files.readAllLines(file);
3✔
1048
      this.context.trace("Completed reading {} lines from file {}", content.size(), file);
16✔
1049
      return content;
2✔
1050
    } catch (IOException e) {
×
1051
      throw new IllegalStateException("Failed to read file " + file, e);
×
1052
    }
1053
  }
1054

1055
  @Override
1056
  public void writeFileLines(List<String> content, Path file, boolean createParentDir) {
1057

1058
    if (createParentDir) {
2!
1059
      mkdirs(file.getParent());
×
1060
    }
1061
    if (content == null) {
2!
1062
      content = List.of();
×
1063
    }
1064
    this.context.trace("Writing content with {} lines to file {}", content.size(), file);
16✔
1065
    if (Files.exists(file)) {
5✔
1066
      this.context.debug("Overriding content of file {}", file);
10✔
1067
    }
1068
    try {
1069
      Files.write(file, content);
6✔
1070
      this.context.trace("Wrote content to file {}", file);
10✔
1071
    } catch (IOException e) {
×
1072
      throw new RuntimeException("Failed to write file " + file, e);
×
1073
    }
1✔
1074
  }
1✔
1075

1076
  @Override
1077
  public void readProperties(Path file, Properties properties) {
1078

1079
    try (Reader reader = Files.newBufferedReader(file)) {
3✔
1080
      properties.load(reader);
3✔
1081
      this.context.debug("Successfully loaded {} properties from {}", properties.size(), file);
16✔
1082
    } catch (IOException e) {
×
1083
      throw new IllegalStateException("Failed to read properties file: " + file, e);
×
1084
    }
1✔
1085
  }
1✔
1086

1087
  @Override
1088
  public void writeProperties(Properties properties, Path file, boolean createParentDir) {
1089

1090
    if (createParentDir) {
2✔
1091
      mkdirs(file.getParent());
4✔
1092
    }
1093
    try (Writer writer = Files.newBufferedWriter(file)) {
5✔
1094
      properties.store(writer, null); // do not get confused - Java still writes a date/time header that cannot be omitted
4✔
1095
      this.context.debug("Successfully saved {} properties to {}", properties.size(), file);
16✔
1096
    } catch (IOException e) {
×
1097
      throw new IllegalStateException("Failed to save properties file during tests.", e);
×
1098
    }
1✔
1099
  }
1✔
1100

1101
  @Override
1102
  public Duration getFileAge(Path path) {
1103
    if (Files.exists(path)) {
5✔
1104
      try {
1105
        long currentTime = System.currentTimeMillis();
2✔
1106
        long fileModifiedTime = Files.getLastModifiedTime(path).toMillis();
6✔
1107
        return Duration.ofMillis(currentTime - fileModifiedTime);
5✔
1108
      } catch (IOException e) {
×
1109
        this.context.warning().log(e, "Could not get modification-time of {}.", path);
×
1110
      }
×
1111
    } else {
1112
      this.context.debug("Path {} is missing - skipping modification-time and file age check.", path);
10✔
1113
    }
1114
    return null;
2✔
1115
  }
1116

1117
  @Override
1118
  public boolean isFileAgeRecent(Path path, Duration cacheDuration) {
1119

1120
    Duration age = getFileAge(path);
4✔
1121
    if (age == null) {
2✔
1122
      return false;
2✔
1123
    }
1124
    context.debug("The path {} was last updated {} ago and caching duration is {}.", path, age, cacheDuration);
18✔
1125
    return (age.toMillis() <= cacheDuration.toMillis());
10✔
1126
  }
1127
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc