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

devonfw / IDEasy / 13562143209

27 Feb 2025 08:35AM UTC coverage: 68.249% (+0.03%) from 68.222%
13562143209

Pull #1078

github

web-flow
Merge 540111889 into 20f52ca6f
Pull Request #1078: #929 optimize upgrade settings using file access

3031 of 4891 branches covered (61.97%)

Branch coverage included in aggregate %.

7867 of 11077 relevant lines covered (71.02%)

3.09 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.os.SystemInfoImpl;
54
import com.devonfw.tools.ide.process.ProcessContext;
55
import com.devonfw.tools.ide.util.DateTimeUtil;
56
import com.devonfw.tools.ide.util.FilenameUtil;
57
import com.devonfw.tools.ide.util.HexUtil;
58

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

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

66
  private static final String WINDOWS_FILE_LOCK_WARNING =
67
      "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"
68
          + WINDOWS_FILE_LOCK_DOCUMENTATION_PAGE;
69

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

72
  private final IdeContext context;
73

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

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

85
  private HttpClient createHttpClient(String url) {
86

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

223
  @Override
224
  public boolean exists(Path file) {
225
    return Files.exists(file);
5✔
226
  }
227

228
  @Override
229
  public boolean isExpectedFolder(Path folder) {
230

231
    if (Files.isDirectory(folder)) {
5✔
232
      return true;
2✔
233
    }
234
    this.context.warning("Expected folder was not found at {}", folder);
10✔
235
    return false;
2✔
236
  }
237

238
  @Override
239
  public String checksum(Path file, String hashAlgorithm) {
240

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

260
  public boolean isJunction(Path path) {
261

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

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

277
  @Override
278
  public Path backup(Path fileOrFolder) {
279

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

300
  private static Path appendParentPath(Path path, Path parent, int max) {
301

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

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

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

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

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

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

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

393
  /**
394
   * 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
395
   * {@link Path} that is neither a symbolic link nor a Windows junction.
396
   *
397
   * @param path the {@link Path} to delete.
398
   * @throws IOException if the actual {@link Files#delete(Path) deletion} fails.
399
   */
400
  private void deleteLinkIfExists(Path path) throws IOException {
401

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

405
    assert !(isSymlink && isJunction);
5!
406

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

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

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

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

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

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

484
  @Override
485
  public void symlink(Path source, Path targetLink, boolean relative) {
486

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

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

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

518
  @Override
519
  public Path toRealPath(Path path) {
520

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

532
  @Override
533
  public Path createTempDir(String name) {
534

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

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

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

596
  private void postExtractHook(Consumer<Path> postExtractHook, Path properInstallDir) {
597

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

603
  /**
604
   * @param path the {@link Path} to start the recursive search from.
605
   * @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
606
   *     item in their respective directory and {@code s} is not named "bin".
607
   */
608
  private Path getProperInstallationSubDirOf(Path path, Path archiveFile) {
609

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

627
  @Override
628
  public void extractZip(Path file, Path targetDir) {
629

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

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

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

666
  @Override
667
  public void extractTar(Path file, Path targetDir, TarCompression compression) {
668

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

672
  @Override
673
  public void extractJar(Path file, Path targetDir) {
674

675
    extractZip(file, targetDir);
4✔
676
  }
1✔
677

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

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

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

694
    return permissionStringBuilder.toString();
3✔
695
  }
696

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

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

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

736
  @Override
737
  public void extractDmg(Path file, Path targetDir) {
738

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

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

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

758
  @Override
759
  public void extractMsi(Path file, Path targetDir) {
760

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

768
  @Override
769
  public void extractPkg(Path file, Path targetDir) {
770

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

781
  @Override
782
  public void delete(Path path) {
783

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

800
  private void deleteRecursive(Path path) throws IOException {
801

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

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

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

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

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

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

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

885
  @Override
886
  public boolean isEmptyDir(Path dir) {
887

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

891
  private long getFileSize(Path file) {
892

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

901
  private long getFileSizeRecursive(Path path) {
902

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

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

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

936
  @Override
937
  public void makeExecutable(Path file, boolean confirm) {
938

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

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

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

984
  @Override
985
  public void touch(Path file) {
986

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

1002
  @Override
1003
  public String readFileContent(Path file) {
1004

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

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

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

1036
  @Override
1037
  public List<String> readFileLines(Path file) {
1038

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

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

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

1074
  @Override
1075
  public void readProperties(Path file, Properties properties) {
1076

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

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

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

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

1115
  @Override
1116
  public boolean isFileAgeRecent(Path path, Duration cacheDuration) {
1117

1118
    Duration age = getFileAge(path);
4✔
1119
    if (age == null) {
2✔
1120
      return false;
2✔
1121
    }
1122
    context.debug("The path {} was last updated {} ago and caching duration is {}.", path, age, cacheDuration);
18✔
1123
    return (age.toMillis() <= cacheDuration.toMillis());
10✔
1124
  }
1125
}
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