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

devonfw / IDEasy / 13327588889

14 Feb 2025 10:44AM UTC coverage: 67.947% (-0.5%) from 68.469%
13327588889

Pull #1021

github

web-flow
Merge d03159bfe into 52609dacb
Pull Request #1021: #786: support ide upgrade to automatically update to the latest version of IDEasy

2964 of 4791 branches covered (61.87%)

Branch coverage included in aggregate %.

7688 of 10886 relevant lines covered (70.62%)

3.07 hits per line

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

65.92
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.attribute.BasicFileAttributes;
24
import java.nio.file.attribute.FileTime;
25
import java.nio.file.attribute.PosixFilePermission;
26
import java.nio.file.attribute.PosixFilePermissions;
27
import java.security.DigestInputStream;
28
import java.security.MessageDigest;
29
import java.security.NoSuchAlgorithmException;
30
import java.time.Duration;
31
import java.time.LocalDateTime;
32
import java.util.ArrayList;
33
import java.util.HashSet;
34
import java.util.Iterator;
35
import java.util.List;
36
import java.util.Map;
37
import java.util.Properties;
38
import java.util.Set;
39
import java.util.function.Consumer;
40
import java.util.function.Function;
41
import java.util.function.Predicate;
42
import java.util.stream.Stream;
43

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

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

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

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

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

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

71
  private final IdeContext context;
72

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

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

84
  private HttpClient createHttpClient(String url) {
85

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

222
  @Override
223
  public boolean isExpectedFolder(Path folder) {
224

225
    if (Files.isDirectory(folder)) {
5!
226
      return true;
2✔
227
    }
228
    this.context.warning("Expected folder was not found at {}", folder);
×
229
    return false;
×
230
  }
231

232
  @Override
233
  public String checksum(Path file, String hashAlgorithm) {
234

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

254
  public boolean isJunction(Path path) {
255

256
    if (!SystemInfoImpl.INSTANCE.isWindows()) {
3!
257
      return false;
2✔
258
    }
259

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

271
  @Override
272
  public Path backup(Path fileOrFolder) {
273

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

294
  private static Path appendParentPath(Path path, Path parent, int max) {
295

296
    if ((parent == null) || (max <= 0)) {
4!
297
      return path;
2✔
298
    }
299
    return appendParentPath(path, parent.getParent(), max - 1).resolve(parent.getFileName());
11✔
300
  }
301

302
  @Override
303
  public void move(Path source, Path targetDir) {
304

305
    this.context.trace("Moving {} to {}", source, targetDir);
14✔
306
    try {
307
      Files.move(source, targetDir);
6✔
308
    } catch (IOException e) {
×
309
      String fileType = Files.isSymbolicLink(source) ? "symlink" : isJunction(source) ? "junction" : Files.isDirectory(source) ? "directory" : "file";
×
310
      String message = "Failed to move " + fileType + ": " + source + " to " + targetDir + ".";
×
311
      if (this.context.getSystemInfo().isWindows()) {
×
312
        message = message + "\n" + WINDOWS_FILE_LOCK_WARNING;
×
313
      }
314
      throw new IllegalStateException(message, e);
×
315
    }
1✔
316
  }
1✔
317

318
  @Override
319
  public void copy(Path source, Path target, FileCopyMode mode, PathCopyListener listener) {
320

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

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

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

387
  /**
388
   * 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
389
   * {@link Path} that is neither a symbolic link nor a Windows junction.
390
   *
391
   * @param path the {@link Path} to delete.
392
   * @throws IOException if the actual {@link Files#delete(Path) deletion} fails.
393
   */
394
  private void deleteLinkIfExists(Path path) throws IOException {
395

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

399
    assert !(isSymlink && isJunction);
5!
400

401
    if (isJunction || isSymlink) {
4!
402
      this.context.info("Deleting previous " + (isJunction ? "junction" : "symlink") + " at " + path);
9!
403
      Files.delete(path);
2✔
404
    }
405
  }
1✔
406

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

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

447
  /**
448
   * Creates a Windows junction at {@code targetLink} pointing to {@code source}.
449
   *
450
   * @param source must be another Windows junction or a directory.
451
   * @param targetLink the location of the Windows junction.
452
   */
453
  private void createWindowsJunction(Path source, Path targetLink) {
454

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

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

478
  @Override
479
  public void symlink(Path source, Path targetLink, boolean relative) {
480

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

489
    try {
490
      deleteLinkIfExists(targetLink);
3✔
491
    } catch (IOException e) {
×
492
      throw new IllegalStateException("Failed to delete previous symlink or Windows junction at " + targetLink, e);
×
493
    }
1✔
494

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

512
  @Override
513
  public Path toRealPath(Path path) {
514

515
    try {
516
      Path realPath = path.toRealPath();
5✔
517
      if (!realPath.equals(path)) {
4✔
518
        this.context.trace("Resolved path {} to {}", path, realPath);
14✔
519
      }
520
      return realPath;
2✔
521
    } catch (IOException e) {
×
522
      throw new IllegalStateException("Failed to get real path for " + path, e);
×
523
    }
524
  }
525

526
  @Override
527
  public Path createTempDir(String name) {
528

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

547
  @Override
548
  public void extract(Path archiveFile, Path targetDir, Consumer<Path> postExtractHook, boolean extract) {
549

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

590
  private void postExtractHook(Consumer<Path> postExtractHook, Path properInstallDir) {
591

592
    if (postExtractHook != null) {
2✔
593
      postExtractHook.accept(properInstallDir);
3✔
594
    }
595
  }
1✔
596

597
  /**
598
   * @param path the {@link Path} to start the recursive search from.
599
   * @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
600
   *     item in their respective directory and {@code s} is not named "bin".
601
   */
602
  private Path getProperInstallationSubDirOf(Path path, Path archiveFile) {
603

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

621
  @Override
622
  public void extractZip(Path file, Path targetDir) {
623

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

641
  @SuppressWarnings("unchecked")
642
  private void onFileCopiedFromZip(Path source, Path target, boolean directory, IdeProgressBar progressBar) {
643

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

660
  @Override
661
  public void extractTar(Path file, Path targetDir, TarCompression compression) {
662

663
    extractArchive(file, targetDir, in -> new TarArchiveInputStream(compression.unpack(in)));
13✔
664
  }
1✔
665

666
  @Override
667
  public void extractJar(Path file, Path targetDir) {
668

669
    extractZip(file, targetDir);
4✔
670
  }
1✔
671

672
  /**
673
   * @param permissions The integer as returned by {@link TarArchiveEntry#getMode()} that represents the file permissions of a file on a Unix file system.
674
   * @return A String representing the file permissions. E.g. "rwxrwxr-x" or "rw-rw-r--"
675
   */
676
  public static String generatePermissionString(int permissions) {
677

678
    // Ensure that only the last 9 bits are considered
679
    permissions &= 0b111111111;
4✔
680

681
    StringBuilder permissionStringBuilder = new StringBuilder("rwxrwxrwx");
5✔
682
    for (int i = 0; i < 9; i++) {
7✔
683
      int mask = 1 << i;
4✔
684
      char currentChar = ((permissions & mask) != 0) ? permissionStringBuilder.charAt(8 - i) : '-';
12✔
685
      permissionStringBuilder.setCharAt(8 - i, currentChar);
6✔
686
    }
687

688
    return permissionStringBuilder.toString();
3✔
689
  }
690

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

693
    this.context.info("Extracting TAR file {} to {}", file, targetDir);
14✔
694
    try (InputStream is = Files.newInputStream(file);
5✔
695
        ArchiveInputStream<?> ais = unpacker.apply(is);
5✔
696
        IdeProgressBar pb = this.context.newProgressbarForExtracting(getFileSize(file))) {
7✔
697

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

730
  @Override
731
  public void extractDmg(Path file, Path targetDir) {
732

733
    this.context.info("Extracting DMG file {} to {}", file, targetDir);
×
734
    assert this.context.getSystemInfo().isMac();
×
735

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

747
    copy(appPath, targetDir, FileCopyMode.COPY_TREE_OVERRIDE_TREE);
×
748
    pc.addArgs("detach", "-force", mountPath);
×
749
    pc.run();
×
750
  }
×
751

752
  @Override
753
  public void extractMsi(Path file, Path targetDir) {
754

755
    this.context.info("Extracting MSI file {} to {}", file, targetDir);
×
756
    this.context.newProcess().executable("msiexec").addArgs("/a", file, "/qn", "TARGETDIR=" + targetDir).run();
×
757
    // msiexec also creates a copy of the MSI
758
    Path msiCopy = targetDir.resolve(file.getFileName());
×
759
    delete(msiCopy);
×
760
  }
×
761

762
  @Override
763
  public void extractPkg(Path file, Path targetDir) {
764

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

775
  @Override
776
  public void delete(Path path) {
777

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

794
  private void deleteRecursive(Path path) throws IOException {
795

796
    if (Files.isDirectory(path)) {
5✔
797
      try (Stream<Path> childStream = Files.list(path)) {
3✔
798
        Iterator<Path> iterator = childStream.iterator();
3✔
799
        while (iterator.hasNext()) {
3✔
800
          Path child = iterator.next();
4✔
801
          deleteRecursive(child);
3✔
802
        }
1✔
803
      }
804
    }
805
    this.context.trace("Deleting {} ...", path);
10✔
806
    Files.delete(path);
2✔
807
  }
1✔
808

809
  @Override
810
  public Path findFirst(Path dir, Predicate<Path> filter, boolean recursive) {
811

812
    try {
813
      if (!Files.isDirectory(dir)) {
5✔
814
        return null;
2✔
815
      }
816
      return findFirstRecursive(dir, filter, recursive);
6✔
817
    } catch (IOException e) {
×
818
      throw new IllegalStateException("Failed to search for file in " + dir, e);
×
819
    }
820
  }
821

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

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

850
  @Override
851
  public List<Path> listChildrenMapped(Path dir, Function<Path, Path> filter) {
852

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

879
  @Override
880
  public boolean isEmptyDir(Path dir) {
881

882
    return listChildren(dir, f -> true).isEmpty();
8✔
883
  }
884

885
  private long getFileSize(Path file) {
886

887
    try {
888
      return Files.size(file);
3✔
889
    } catch (IOException e) {
×
890
      this.context.warning(e.getMessage(), e);
×
891
      return 0;
×
892
    }
893
  }
894

895
  private long getFileSizeRecursive(Path path) {
896

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

914
  @Override
915
  public Path findExistingFile(String fileName, List<Path> searchDirs) {
916

917
    for (Path dir : searchDirs) {
×
918
      Path filePath = dir.resolve(fileName);
×
919
      try {
920
        if (Files.exists(filePath)) {
×
921
          return filePath;
×
922
        }
923
      } catch (Exception e) {
×
924
        throw new IllegalStateException("Unexpected error while checking existence of file " + filePath + " .", e);
×
925
      }
×
926
    }
×
927
    return null;
×
928
  }
929

930
  @Override
931
  public void makeExecutable(Path file, boolean confirm) {
932

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

942
        // Add execute permission for all users
943
        Set<PosixFilePermission> executablePermissions = new HashSet<>(existingPermissions);
5✔
944
        boolean update = false;
2✔
945
        update |= executablePermissions.add(PosixFilePermission.OWNER_EXECUTE);
6✔
946
        update |= executablePermissions.add(PosixFilePermission.GROUP_EXECUTE);
6✔
947
        update |= executablePermissions.add(PosixFilePermission.OTHERS_EXECUTE);
6✔
948

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

978
  @Override
979
  public void touch(Path file) {
980

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

996
  @Override
997
  public String readFileContent(Path file) {
998

999
    this.context.trace("Reading content of file from {}", file);
10✔
1000
    try {
1001
      String content = Files.readString(file);
3✔
1002
      this.context.trace("Completed reading {} character(s) from file {}", content.length(), file);
16✔
1003
      return content;
2✔
1004
    } catch (IOException e) {
×
1005
      throw new IllegalStateException("Failed to read file " + file, e);
×
1006
    }
1007
  }
1008

1009
  @Override
1010
  public void writeFileContent(String content, Path file, boolean createParentDir) {
1011

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

1030
  @Override
1031
  public List<String> readFileLines(Path file) {
1032

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

1047
  @Override
1048
  public void writeFileLines(List<String> content, Path file, boolean createParentDir) {
1049

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

1068
  @Override
1069
  public void readProperties(Path file, Properties properties) {
1070

1071
    try (Reader reader = Files.newBufferedReader(file)) {
3✔
1072
      properties.load(reader);
3✔
1073
      this.context.debug("Successfully loaded {} properties from {}", properties.size(), file);
16✔
1074
    } catch (IOException e) {
×
1075
      throw new IllegalStateException("Failed to read properties file: " + file, e);
×
1076
    }
1✔
1077
  }
1✔
1078

1079
  @Override
1080
  public void writeProperties(Properties properties, Path file, boolean createParentDir) {
1081

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

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

1109
  @Override
1110
  public boolean isFileAgeRecent(Path path, Duration cacheDuration) {
1111

1112
    Duration age = getFileAge(path);
4✔
1113
    if (age == null) {
2✔
1114
      return false;
2✔
1115
    }
1116
    context.debug("The path {} was last updated {} ago and caching duration is {}.", path, age, cacheDuration);
18✔
1117
    return (age.toMillis() <= cacheDuration.toMillis());
10✔
1118
  }
1119
}
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