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

devonfw / IDEasy / 27742167567

18 Jun 2026 06:52AM UTC coverage: 71.279% (-0.006%) from 71.285%
27742167567

push

github

web-flow
#797: zip symlink pure java (#1995)

Co-authored-by: Jörg Hohwiller <hohwille@users.noreply.github.com>

4675 of 7252 branches covered (64.46%)

Branch coverage included in aggregate %.

12050 of 16212 relevant lines covered (74.33%)

3.15 hits per line

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

67.89
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.FileOutputStream;
5
import java.io.IOException;
6
import java.io.InputStream;
7
import java.io.OutputStream;
8
import java.io.Reader;
9
import java.io.Writer;
10
import java.net.http.HttpClient.Version;
11
import java.net.http.HttpResponse;
12
import java.nio.charset.StandardCharsets;
13
import java.nio.file.FileSystemException;
14
import java.nio.file.Files;
15
import java.nio.file.LinkOption;
16
import java.nio.file.NoSuchFileException;
17
import java.nio.file.Path;
18
import java.nio.file.StandardCopyOption;
19
import java.nio.file.attribute.BasicFileAttributes;
20
import java.nio.file.attribute.DosFileAttributeView;
21
import java.nio.file.attribute.FileTime;
22
import java.nio.file.attribute.PosixFileAttributeView;
23
import java.nio.file.attribute.PosixFilePermission;
24
import java.security.DigestInputStream;
25
import java.security.MessageDigest;
26
import java.security.NoSuchAlgorithmException;
27
import java.time.Duration;
28
import java.time.LocalDateTime;
29
import java.util.ArrayList;
30
import java.util.Enumeration;
31
import java.util.HashSet;
32
import java.util.Iterator;
33
import java.util.List;
34
import java.util.Objects;
35
import java.util.Properties;
36
import java.util.Set;
37
import java.util.function.Consumer;
38
import java.util.function.Function;
39
import java.util.function.Predicate;
40
import java.util.stream.Stream;
41

42
import org.apache.commons.compress.archivers.ArchiveEntry;
43
import org.apache.commons.compress.archivers.ArchiveInputStream;
44
import org.apache.commons.compress.archivers.ArchiveOutputStream;
45
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
46
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
47
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
48
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
49
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
50
import org.apache.commons.compress.archivers.zip.ZipFile;
51
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;
52
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
53
import org.apache.commons.compress.compressors.gzip.GzipParameters;
54
import org.apache.commons.io.IOUtils;
55
import org.slf4j.Logger;
56
import org.slf4j.LoggerFactory;
57

58
import com.devonfw.tools.ide.cli.CliException;
59
import com.devonfw.tools.ide.context.IdeContext;
60
import com.devonfw.tools.ide.io.ini.IniComment;
61
import com.devonfw.tools.ide.io.ini.IniFile;
62
import com.devonfw.tools.ide.io.ini.IniSection;
63
import com.devonfw.tools.ide.os.SystemInfoImpl;
64
import com.devonfw.tools.ide.process.ProcessContext;
65
import com.devonfw.tools.ide.process.ProcessMode;
66
import com.devonfw.tools.ide.process.ProcessResult;
67
import com.devonfw.tools.ide.util.DateTimeUtil;
68
import com.devonfw.tools.ide.util.FilenameUtil;
69
import com.devonfw.tools.ide.util.HexUtil;
70
import com.devonfw.tools.ide.variable.IdeVariables;
71

72
/**
73
 * Implementation of {@link FileAccess}.
74
 */
75
public class FileAccessImpl extends HttpDownloader implements FileAccess {
76

77
  private static final Logger LOG = LoggerFactory.getLogger(FileAccessImpl.class);
4✔
78

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

81
  private static final String WINDOWS_FILE_LOCK_WARNING =
82
      "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"
83
          + WINDOWS_FILE_LOCK_DOCUMENTATION_PAGE;
84

85
  private final IdeContext context;
86

87
  /**
88
   * The constructor.
89
   *
90
   * @param context the {@link IdeContext} to use.
91
   */
92
  public FileAccessImpl(IdeContext context) {
93

94
    super();
2✔
95
    this.context = context;
3✔
96
  }
1✔
97

98
  @Override
99
  public void download(String url, Path target) {
100

101
    if (url.startsWith("http")) {
4✔
102
      downloadViaHttp(url, target);
5✔
103
    } else if (url.startsWith("ftp") || url.startsWith("sftp")) {
8!
104
      throw new IllegalArgumentException("Unsupported download URL: " + url);
×
105
    } else {
106
      Path source = Path.of(url);
5✔
107
      if (isFile(source)) {
4!
108
        // network drive
109
        copyFileWithProgressBar(source, target);
5✔
110
      } else {
111
        throw new IllegalArgumentException("Download path does not point to a downloadable file: " + url);
×
112
      }
113
    }
114
  }
1✔
115

116
  private void downloadViaHttp(String url, Path target) {
117

118
    List<Version> httpProtocols = IdeVariables.HTTP_VERSIONS.get(this.context);
6✔
119
    Exception lastException = null;
2✔
120
    if (httpProtocols.isEmpty()) {
3!
121
      try {
122
        downloadWithHttpVersion(url, target, null);
5✔
123
        return;
1✔
124
      } catch (Exception e) {
×
125
        lastException = e;
×
126
      }
×
127
    } else {
128
      for (Version version : httpProtocols) {
×
129
        try {
130
          downloadWithHttpVersion(url, target, version);
×
131
          return;
×
132
        } catch (Exception ex) {
×
133
          lastException = ex;
×
134
        }
135
      }
×
136
    }
137
    throw new IllegalStateException("Failed to download file from URL " + url + " to " + target, lastException);
×
138
  }
139

140
  private void downloadWithHttpVersion(String url, Path target, Version httpVersion) throws Exception {
141

142
    if (httpVersion == null) {
2!
143
      LOG.info("Trying to download {} from {}", target.getFileName(), url);
7✔
144
    } else {
145
      LOG.info("Trying to download {} from {} with HTTP protocol version {}", target.getFileName(), url, httpVersion);
×
146
    }
147
    mkdirs(target.getParent());
4✔
148
    this.context.getNetworkStatus().invokeNetworkTask(() ->
11✔
149
    {
150
      httpGet(url, httpVersion, (response) -> downloadFileWithProgressBar(url, target, response));
13✔
151
      return null;
2✔
152
    }, url);
153
  }
1✔
154

155
  /**
156
   * Downloads a file while showing a {@link IdeProgressBar}.
157
   *
158
   * @param url the url to download.
159
   * @param target Path of the target directory.
160
   * @param response the {@link HttpResponse} to use.
161
   */
162
  private void downloadFileWithProgressBar(String url, Path target, HttpResponse<InputStream> response) {
163

164
    long contentLength = response.headers().firstValueAsLong("content-length").orElse(-1);
7✔
165
    if (contentLength < 0) {
4✔
166
      LOG.warn("Content-Length was not provided by download from {}", url);
4✔
167
    }
168

169
    byte[] data = new byte[1024];
3✔
170
    boolean fileComplete = false;
2✔
171
    int count;
172

173
    try (InputStream body = response.body();
4✔
174
        FileOutputStream fileOutput = new FileOutputStream(target.toFile());
6✔
175
        BufferedOutputStream bufferedOut = new BufferedOutputStream(fileOutput, data.length);
7✔
176
        IdeProgressBar pb = this.context.newProgressBarForDownload(contentLength)) {
5✔
177
      while (!fileComplete) {
2✔
178
        count = body.read(data);
4✔
179
        if (count <= 0) {
2✔
180
          fileComplete = true;
3✔
181
        } else {
182
          bufferedOut.write(data, 0, count);
5✔
183
          pb.stepBy(count);
5✔
184
        }
185
      }
186
    } catch (Exception e) {
×
187
      throw new RuntimeException(e);
×
188
    }
1✔
189
  }
1✔
190

191
  private void copyFileWithProgressBar(Path source, Path target) {
192

193
    long size = getFileSize(source);
4✔
194
    if (size < 100_000) {
4✔
195
      copy(source, target, FileCopyMode.COPY_FILE_TO_TARGET_OVERRIDE);
5✔
196
      return;
1✔
197
    }
198
    try (InputStream in = Files.newInputStream(source); OutputStream out = Files.newOutputStream(target)) {
10✔
199
      byte[] buf = new byte[1024];
3✔
200
      try (IdeProgressBar pb = this.context.newProgressbarForCopying(size)) {
5✔
201
        int readBytes;
202
        while ((readBytes = in.read(buf)) > 0) {
6✔
203
          out.write(buf, 0, readBytes);
5✔
204
          pb.stepBy(readBytes);
5✔
205
        }
206
      } catch (Exception e) {
×
207
        throw new RuntimeException(e);
×
208
      }
1✔
209
    } catch (IOException e) {
×
210
      throw new RuntimeException("Failed to copy from " + source + " to " + target, e);
×
211
    }
1✔
212
  }
1✔
213

214
  @Override
215
  public String download(String url) {
216

217
    LOG.debug("Downloading text body from {}", url);
4✔
218
    return httpGetAsString(url);
3✔
219
  }
220

221
  @Override
222
  public void mkdirs(Path directory) {
223

224
    if (Files.isDirectory(directory)) {
5✔
225
      return;
1✔
226
    }
227
    LOG.trace("Creating directory {}", directory);
4✔
228
    try {
229
      Files.createDirectories(directory);
5✔
230
    } catch (IOException e) {
×
231
      throw new IllegalStateException("Failed to create directory " + directory, e);
×
232
    }
1✔
233
  }
1✔
234

235
  @Override
236
  public boolean isFile(Path file) {
237

238
    if (!Files.exists(file)) {
5!
239
      LOG.trace("File {} does not exist", file);
×
240
      return false;
×
241
    }
242
    if (Files.isDirectory(file)) {
5!
243
      LOG.trace("Path {} is a directory but a regular file was expected", file);
×
244
      return false;
×
245
    }
246
    return true;
2✔
247
  }
248

249
  @Override
250
  public boolean isExpectedFolder(Path folder) {
251

252
    if (Files.isDirectory(folder)) {
5✔
253
      return true;
2✔
254
    }
255
    LOG.warn("Expected folder was not found at {}", folder);
4✔
256
    return false;
2✔
257
  }
258

259
  @Override
260
  public String checksum(Path file, String hashAlgorithm) {
261

262
    MessageDigest md;
263
    try {
264
      md = MessageDigest.getInstance(hashAlgorithm);
3✔
265
    } catch (NoSuchAlgorithmException e) {
×
266
      throw new IllegalStateException("No such hash algorithm " + hashAlgorithm, e);
×
267
    }
1✔
268
    byte[] buffer = new byte[1024];
3✔
269
    try (InputStream is = Files.newInputStream(file); DigestInputStream dis = new DigestInputStream(is, md)) {
11✔
270
      int read = 0;
2✔
271
      while (read >= 0) {
2✔
272
        read = dis.read(buffer);
5✔
273
      }
274
    } catch (Exception e) {
×
275
      throw new IllegalStateException("Failed to read and hash file " + file, e);
×
276
    }
1✔
277
    byte[] digestBytes = md.digest();
3✔
278
    return HexUtil.toHexString(digestBytes);
3✔
279
  }
280

281
  @Override
282
  public boolean isJunction(Path path) {
283

284
    if (!SystemInfoImpl.INSTANCE.isWindows()) {
3!
285
      return false;
2✔
286
    }
287
    try {
288
      BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
×
289
      return attr.isOther() && attr.isDirectory();
×
290
    } catch (NoSuchFileException e) {
×
291
      return false; // file doesn't exist
×
292
    } catch (IOException e) {
×
293
      // For broken junctions, reading attributes might fail with various IOExceptions.
294
      // In such cases, we should check if the path exists without following links.
295
      // If it exists but we can't read its attributes, it's likely a broken junction.
296
      if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
×
297
        LOG.debug("Path {} exists but attributes cannot be read, likely a broken junction: {}", path, e.getMessage());
×
298
        return true; // Assume it's a broken junction
×
299
      }
300
      // If it doesn't exist at all, it's not a junction
301
      return false;
×
302
    }
303
  }
304

305
  @Override
306
  public Path backup(Path fileOrFolder) {
307

308
    if ((fileOrFolder != null) && (Files.isSymbolicLink(fileOrFolder) || isJunction(fileOrFolder))) {
9!
309
      delete(fileOrFolder);
4✔
310
    } else if ((fileOrFolder != null) && Files.exists(fileOrFolder)) {
7!
311
      LOG.trace("Going to backup {}", fileOrFolder);
4✔
312
      LocalDateTime now = LocalDateTime.now();
2✔
313
      String date = DateTimeUtil.formatDate(now, true);
4✔
314
      String time = DateTimeUtil.formatTime(now);
3✔
315
      String filename = fileOrFolder.getFileName().toString();
4✔
316
      Path backupBaseDir = this.context.getIdeHome();
4✔
317
      if (backupBaseDir == null) {
2!
318
        backupBaseDir = this.context.getIdePath();
×
319
      }
320
      Path backupPath = backupBaseDir.resolve(IdeContext.FOLDER_BACKUPS).resolve(date).resolve(time + "_" + filename);
10✔
321
      backupPath = appendParentPath(backupPath, fileOrFolder.getParent(), 2);
6✔
322
      mkdirs(backupPath);
3✔
323
      Path target = backupPath.resolve(filename);
4✔
324
      LOG.info("Creating backup by moving {} to {}", fileOrFolder, target);
5✔
325
      move(fileOrFolder, target);
6✔
326
      return target;
2✔
327
    } else {
328
      LOG.trace("Backup of {} skipped as the path does not exist.", fileOrFolder);
4✔
329
    }
330
    return fileOrFolder;
2✔
331
  }
332

333
  private static Path appendParentPath(Path path, Path parent, int max) {
334

335
    if ((parent == null) || (max <= 0)) {
4!
336
      return path;
2✔
337
    }
338
    return appendParentPath(path, parent.getParent(), max - 1).resolve(parent.getFileName());
11✔
339
  }
340

341
  @Override
342
  public void move(Path source, Path targetDir, StandardCopyOption... copyOptions) {
343

344
    LOG.trace("Moving {} to {}", source, targetDir);
5✔
345
    try {
346
      Files.move(source, targetDir, copyOptions);
5✔
347
    } catch (IOException e) {
×
348
      String fileType = Files.isSymbolicLink(source) ? "symlink" : isJunction(source) ? "junction" : Files.isDirectory(source) ? "directory" : "file";
×
349
      String message = "Failed to move " + fileType + ": " + source + " to " + targetDir + ".";
×
350
      if (this.context.getSystemInfo().isWindows()) {
×
351
        message = message + "\n" + WINDOWS_FILE_LOCK_WARNING;
×
352
      }
353
      throw new IllegalStateException(message, e);
×
354
    }
1✔
355
  }
1✔
356

357
  @Override
358
  public void copy(Path source, Path target, FileCopyMode mode, PathCopyListener listener) {
359

360
    if (mode.isUseSourceFilename()) {
3✔
361
      // if we want to copy the file or folder "source" to the existing folder "target" in a shell this will copy
362
      // source into that folder so that we as a result have a copy in "target/source".
363
      // With Java NIO the raw copy method will fail as we cannot copy "source" to the path of the "target" folder.
364
      // For folders we want the same behavior as the linux "cp -r" command so that the "source" folder is copied
365
      // and not only its content what also makes it consistent with the move method that also behaves this way.
366
      // Therefore we need to add the filename (foldername) of "source" to the "target" path before.
367
      // For the rare cases, where we want to copy the content of a folder (cp -r source/* target) we support
368
      // it via the COPY_TREE_CONTENT mode.
369
      Path fileName = source.getFileName();
3✔
370
      if (fileName != null) { // if filename is null, we are copying the root of a (virtual filesystem)
2!
371
        target = target.resolve(fileName.toString());
5✔
372
      }
373
    }
374
    boolean fileOnly = mode.isFileOnly();
3✔
375
    String operation = mode.getOperation();
3✔
376
    if (mode.isExtract()) {
3!
377
      LOG.debug("Starting to {} to {}", operation, target);
×
378
    } else {
379
      if (fileOnly) {
2✔
380
        LOG.debug("Starting to {} file {} to {}", operation, source, target);
18✔
381
      } else {
382
        LOG.debug("Starting to {} {} recursively to {}", operation, source, target);
17✔
383
      }
384
    }
385
    if (fileOnly && Files.isDirectory(source)) {
7!
386
      throw new IllegalStateException("Expected file but found a directory to copy at " + source);
×
387
    }
388
    if (mode.isFailIfExists()) {
3✔
389
      if (Files.exists(target)) {
5!
390
        throw new IllegalStateException("Failed to " + operation + " " + source + " to already existing target " + target);
×
391
      }
392
    } else if (mode == FileCopyMode.COPY_TREE_OVERRIDE_TREE) {
3✔
393
      delete(target);
3✔
394
    }
395
    try {
396
      copyRecursive(source, target, mode, listener);
6✔
397
    } catch (IOException e) {
×
398
      throw new IllegalStateException("Failed to " + operation + " " + source + " to " + target, e);
×
399
    }
1✔
400
  }
1✔
401

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

404
    if (Files.isDirectory(source)) {
5✔
405
      mkdirs(target);
3✔
406
      try (Stream<Path> childStream = Files.list(source)) {
3✔
407
        Iterator<Path> iterator = childStream.iterator();
3✔
408
        while (iterator.hasNext()) {
3✔
409
          Path child = iterator.next();
4✔
410
          copyRecursive(child, target.resolve(child.getFileName().toString()), mode, listener);
10✔
411
        }
1✔
412
      }
413
      listener.onCopy(source, target, true);
6✔
414
    } else if (Files.exists(source)) {
5!
415
      if (mode.isOverride()) {
3✔
416
        delete(target);
3✔
417
      }
418
      LOG.trace("Starting to {} {} to {}", mode.getOperation(), source, target);
18✔
419
      Files.copy(source, target);
6✔
420
      listener.onCopy(source, target, false);
6✔
421
    } else {
422
      throw new IOException("Path " + source + " does not exist.");
×
423
    }
424
  }
1✔
425

426
  /**
427
   * Deletes the given {@link Path} if it is a symbolic link or a Windows junction or hard link. And throws an {@link IllegalStateException} if it fails to
428
   * delete the file at the given {@link Path}.
429
   *
430
   * @param path the {@link Path} to delete.
431
   */
432
  private void deleteLinkIfExists(Path path) {
433

434
    boolean isJunction = isJunction(path); // since broken junctions are not detected by Files.exists()
4✔
435
    boolean exists = Files.exists(path, LinkOption.NOFOLLOW_LINKS);
9✔
436

437
    if (isJunction || exists) {
4!
438
      LOG.info("Deleting previous link or file at " + path);
5✔
439
      try {
440
        Files.delete(path);
2✔
441
      } catch (IOException e) {
×
442
        throw new IllegalStateException("Failed to delete link or file at " + path, e);
×
443
      }
1✔
444
    }
445
  }
1✔
446

447
  /**
448
   * Computes the relative target {@link Path} to use for a relative symbolic link at {@code link} pointing to {@code source}.
449
   *
450
   * @param source the {@link Path} the link should point to.
451
   * @param link the absolute, normalized destination {@link Path} of the link.
452
   * @return the relative {@link Path} from the parent of {@code link} to {@code source}.
453
   */
454
  private Path relativizeSource(Path source, Path link) {
455

456
    if (!source.isAbsolute()) {
3✔
457
      source = link.resolveSibling(source);
4✔
458
    }
459
    source = source.toAbsolutePath().normalize();
4✔
460
    return preserveSelfReference(link.getParent().relativize(source));
6✔
461
  }
462

463
  /**
464
   * {@link Path#normalize()} and {@link Path#relativize(Path)} can produce the empty path when the result would be the current directory. {@code "."} is the
465
   * usable equivalent for a symbolic link target.
466
   */
467
  private static Path preserveSelfReference(Path path) {
468

469
    return path.toString().isEmpty() ? Path.of(".") : path;
11✔
470
  }
471

472
  /**
473
   * Creates a Windows link using mklink at {@code link} pointing to {@code target}.
474
   *
475
   * @param source the {@link Path} the link will point to.
476
   * @param link the {@link Path} where to create the link.
477
   * @param type the {@link PathLinkType}.
478
   */
479
  private void mklinkOnWindows(Path source, Path absoluteSource, Path link, PathLinkType type, boolean relative) {
480

481
    Path finalSource = relative ? source : absoluteSource;
×
482
    Path finalLink = link;
×
483
    Path cwd = null;
×
484
    if (relative) {
×
485
      int count = getCommonNameCount(absoluteSource, link);
×
486
      if (count < 1) {
×
487
        LOG.error("Cannot create relative link at {} pointing to {} - falling back to absolute link", link, absoluteSource);
×
488
      } else {
489
        cwd = getPathStart(absoluteSource, count - 1);
×
490
        finalSource = getPathEnd(absoluteSource, count);
×
491
        finalLink = getPathEnd(link, count);
×
492
      }
493
    }
494

495
    String option = type.getMklinkOption();
×
496
    if (type == PathLinkType.SYMBOLIC_LINK) {
×
497
      boolean directoryTarget = Files.isDirectory(absoluteSource);
×
498
      option = directoryTarget ? "/j" : "/d";
×
499
    }
500

501
    if (!runMklink(finalSource, finalLink, cwd, option)) {
×
502
      throw new IllegalStateException("Failed to create Windows link at " + link + " pointing to " + source);
×
503
    }
504
  }
×
505

506
  private boolean runMklink(Path source, Path link, Path cwd, String option) {
507

508
    LOG.trace("Creating a Windows link with mklink {} at {} pointing to {}", option, link, source);
×
509
    ProcessContext pc = this.context.newProcess().executable("cmd").addArgs("/c", "mklink", option);
×
510
    if (cwd != null) {
×
511
      pc.directory(cwd);
×
512
    }
513
    ProcessResult result = pc.addArgs(link.toString(), source.toString()).run(ProcessMode.DEFAULT);
×
514
    try {
515
      result.failOnError();
×
516
      return true;
×
517
    } catch (RuntimeException e) {
×
518
      LOG.debug("mklink {} failed for {} -> {}: {}", option, link, source, e.getMessage());
×
519
      return false;
×
520
    }
521
  }
522

523
  @Override
524
  public void link(Path source, Path link, boolean relative, PathLinkType type) {
525

526
    Path absoluteLink = link.toAbsolutePath().normalize();
4✔
527
    // Keep this lexical only: archive symlinks may point through links that are created later.
528
    Path finalSource = relative ? relativizeSource(source, absoluteLink) : preserveSelfReference(source.normalize());
11✔
529
    Path absoluteSource = finalSource.isAbsolute() ? finalSource : absoluteLink.getParent().resolve(finalSource).normalize();
11✔
530
    LOG.debug("Creating {} at {} pointing to {} (relative={})", type, link, finalSource, relative);
22✔
531
    deleteLinkIfExists(link);
3✔
532
    try {
533
      // Attention: JavaDoc and position of path arguments can be very confusing - see comment in #1736
534
      if (type == PathLinkType.SYMBOLIC_LINK) {
3!
535
        Files.createSymbolicLink(link, finalSource);
7✔
536
      } else if (type == PathLinkType.HARD_LINK) {
×
537
        createHardLink(absoluteSource, link);
×
538
      } else {
539
        throw new IllegalStateException("" + type);
×
540
      }
541
    } catch (FileSystemException e) {
×
542
      if (SystemInfoImpl.INSTANCE.isWindows()) {
×
543
        LOG.info(
×
544
            "Due to lack of permissions, Microsoft's mklink with junction had to be used to create a Symlink. See\n"
545
                + "https://github.com/devonfw/IDEasy/blob/main/documentation/symlink.adoc for further details. Error was: "
546
                + e.getMessage());
×
547

548
        try {
549
          mklinkOnWindows(finalSource, absoluteSource, absoluteLink, type, relative);
×
550
        } catch (IllegalStateException mkEx) {
×
551
          LOG.info("Creating a hard link as a fallback for the failed mklink attempt.");
×
552
          createHardLink(absoluteSource, link);
×
553
        }
×
554
      } else {
555
        throw new RuntimeException(e);
×
556
      }
557
    } catch (IOException e) {
×
558
      throw new IllegalStateException("Failed to create " + type + " at " + link + " pointing to " + source + " (relative=" + relative + ")", e);
×
559
    }
1✔
560
  }
1✔
561

562

563
  /**
564
   * Creates a hard link at {@code link} pointing to {@code source}.
565
   *
566
   * @param source the {@link Path} the hard link will point to.
567
   * @param link the {@link Path} where to create the hard link.
568
   */
569
  void createHardLink(Path source, Path link) {
570
    try {
571
      Files.createLink(link, source);
×
572
      LOG.trace("Created hard link at {} pointing to {}", link, source);
×
573
    } catch (IOException e) {
×
574
      throw new RuntimeException("Failed to create a hardlink for " + source + " at " + link, e);
×
575
    }
×
576
  }
×
577

578
  @Override
579
  public Path getPathStart(Path path, int nameEnd) {
580

581
    int count = path.getNameCount();
3✔
582
    int delta = count - nameEnd - 1;
6✔
583
    if (delta < 0) {
2!
584
      throw new IllegalArgumentException("Cannot get start before segment " + nameEnd + " from path " + path + " that has only " + count + " segments.");
×
585
    }
586
    Path result = path;
2✔
587
    while (delta > 0) {
2✔
588
      result = result.getParent();
3✔
589
      delta--;
2✔
590
    }
591
    return result;
2✔
592
  }
593

594
  @Override
595
  public Path getPathEnd(Path path, int nameStart) {
596

597
    int count = path.getNameCount();
3✔
598
    if (nameStart > count) {
3!
599
      throw new IllegalArgumentException("Cannot get end after segment " + nameStart + " from path " + path + " that has only " + count + " segments.");
×
600
    } else if (nameStart == count) {
3!
601
      return Path.of(".");
×
602
    }
603
    Path result = path.getName(nameStart++);
5✔
604
    while (nameStart < count) {
3✔
605
      result = result.resolve(path.getName(nameStart++));
8✔
606
    }
607
    return result;
2✔
608
  }
609

610
  @Override
611
  public int getCommonNameCount(Path path1, Path path2) {
612

613
    if ((path1 == null) || (path2 == null) || !Objects.equals(path1.getRoot(), path2.getRoot())) {
10✔
614
      return -1;
2✔
615
    }
616
    int minNameCount = Math.min(path1.getNameCount(), path2.getNameCount());
6✔
617
    int i = 0;
2✔
618
    while (i < minNameCount) {
3!
619
      Path segment1 = path1.getName(i);
4✔
620
      Path segment2 = path2.getName(i);
4✔
621
      if (!segment1.equals(segment2)) {
4✔
622
        break;
1✔
623
      }
624
      i++;
1✔
625
    }
1✔
626
    return i;
2✔
627
  }
628

629
  @Override
630
  public Path toRealPath(Path path) {
631

632
    return toRealPath(path, true);
5✔
633
  }
634

635
  @Override
636
  public Path toCanonicalPath(Path path) {
637

638
    return toRealPath(path, false);
5✔
639
  }
640

641
  private Path toRealPath(Path path, boolean resolveLinks) {
642

643
    try {
644
      Path realPath;
645
      if (resolveLinks) {
2✔
646
        realPath = path.toRealPath();
6✔
647
      } else {
648
        realPath = path.toRealPath(LinkOption.NOFOLLOW_LINKS);
9✔
649
      }
650
      if (!realPath.equals(path)) {
4✔
651
        LOG.trace("Resolved path {} to {}", path, realPath);
5✔
652
      }
653
      return realPath;
2✔
654
    } catch (IOException e) {
×
655
      throw new IllegalStateException("Failed to get real path for " + path, e);
×
656
    }
657
  }
658

659
  @Override
660
  public Path createTempDir(String name) {
661

662
    try {
663
      Path tmp = this.context.getTempPath();
4✔
664
      Path tempDir = tmp.resolve(name);
4✔
665
      int tries = 1;
2✔
666
      while (Files.exists(tempDir)) {
5!
667
        long id = System.nanoTime() & 0xFFFF;
×
668
        tempDir = tmp.resolve(name + "-" + id);
×
669
        tries++;
×
670
        if (tries > 200) {
×
671
          throw new IOException("Unable to create unique name!");
×
672
        }
673
      }
×
674
      return Files.createDirectory(tempDir);
5✔
675
    } catch (IOException e) {
×
676
      throw new IllegalStateException("Failed to create temporary directory with prefix '" + name + "'!", e);
×
677
    }
678
  }
679

680
  @Override
681
  public void extract(Path archiveFile, Path targetDir, Consumer<Path> postExtractHook, boolean extract) {
682

683
    if (Files.isDirectory(archiveFile)) {
5✔
684
      LOG.warn("Found directory for download at {} hence copying without extraction!", archiveFile);
4✔
685
      copy(archiveFile, targetDir, FileCopyMode.COPY_TREE_CONTENT);
5✔
686
      postExtractHook(postExtractHook, targetDir);
4✔
687
      return;
1✔
688
    } else if (!extract) {
2✔
689
      mkdirs(targetDir);
3✔
690
      move(archiveFile, targetDir.resolve(archiveFile.getFileName()));
9✔
691
      return;
1✔
692
    }
693
    Path tmpDir = createTempDir("extract-" + archiveFile.getFileName());
7✔
694
    LOG.trace("Trying to extract the file {} to {} and move it to {}.", archiveFile, tmpDir, targetDir);
17✔
695
    String filename = archiveFile.getFileName().toString();
4✔
696
    TarCompression tarCompression = TarCompression.of(filename);
3✔
697
    if (tarCompression != null) {
2✔
698
      extractTar(archiveFile, tmpDir, tarCompression);
6✔
699
    } else {
700
      String extension = FilenameUtil.getExtension(filename);
3✔
701
      if (extension == null) {
2!
702
        throw new IllegalStateException("Unknown archive format without extension - can not extract " + archiveFile);
×
703
      } else {
704
        LOG.trace("Determined file extension {}", extension);
4✔
705
      }
706
      switch (extension) {
8!
707
        case "zip" -> extractZip(archiveFile, tmpDir);
×
708
        case "jar" -> extractJar(archiveFile, tmpDir);
5✔
709
        case "dmg" -> extractDmg(archiveFile, tmpDir);
×
710
        case "msi" -> extractMsi(archiveFile, tmpDir);
×
711
        case "pkg" -> extractPkg(archiveFile, tmpDir);
×
712
        default -> throw new IllegalStateException("Unknown archive format " + extension + ". Can not extract " + archiveFile);
×
713
      }
714
    }
715
    Path properInstallDir = getProperInstallationSubDirOf(tmpDir, archiveFile);
5✔
716
    postExtractHook(postExtractHook, properInstallDir);
4✔
717
    move(properInstallDir, targetDir);
6✔
718
    delete(tmpDir);
3✔
719
  }
1✔
720

721
  private void postExtractHook(Consumer<Path> postExtractHook, Path properInstallDir) {
722

723
    if (postExtractHook != null) {
2✔
724
      postExtractHook.accept(properInstallDir);
3✔
725
    }
726
  }
1✔
727

728
  /**
729
   * @param path the {@link Path} to start the recursive search from.
730
   * @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
731
   *     item in their respective directory and {@code s} is not named "bin".
732
   */
733
  private Path getProperInstallationSubDirOf(Path path, Path archiveFile) {
734

735
    try (Stream<Path> stream = Files.list(path)) {
3✔
736
      Path[] subFiles = stream.toArray(Path[]::new);
8✔
737
      if (subFiles.length == 0) {
3!
738
        throw new CliException("The downloaded package " + archiveFile + " seems to be empty as you can check in the extracted folder " + path);
×
739
      } else if (subFiles.length == 1) {
4✔
740
        String filename = subFiles[0].getFileName().toString();
6✔
741
        if (!filename.equals(IdeContext.FOLDER_BIN) && !filename.equals(IdeContext.FOLDER_CONTENTS) && !filename.endsWith(".app") && Files.isDirectory(
19!
742
            subFiles[0])) {
743
          return getProperInstallationSubDirOf(subFiles[0], archiveFile);
9✔
744
        }
745
      }
746
      return path;
4✔
747
    } catch (IOException e) {
4!
748
      throw new IllegalStateException("Failed to get sub-files of " + path);
×
749
    }
750
  }
751

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

755
    LOG.info("Extracting ZIP file {} to {}", file, targetDir);
5✔
756
    extractZipWithJava(file, targetDir);
4✔
757
  }
1✔
758

759
  /**
760
   * Extracts a ZIP archive to the given target directory using Java (commons-compress {@link ZipFile}).
761
   * <p>
762
   * Symlinks are handled in a two-phase approach: all regular files and directories are written first, and symlinks are collected and created afterwards.
763
   * Creating the links does not require resolving their targets, so chained macOS {@code .framework} links can be restored.
764
   * <p>
765
   * {@link ZipFile} is used instead of {@link org.apache.commons.compress.archivers.zip.ZipArchiveInputStream} because Unix file attributes (needed for symlink
766
   * detection and permission restoration) are stored in the ZIP central directory at the end of the file. A sequential stream only sees the local file headers,
767
   * where external attributes are always zero. {@link ZipFile} reads the central directory via random access, so attributes are always correct.
768
   *
769
   * @param file the ZIP archive to extract.
770
   * @param targetDir the directory to extract into.
771
   */
772
  private void extractZipWithJava(Path file, Path targetDir) {
773

774
    final List<PathLink> links = new ArrayList<>();
4✔
775
    try (ZipFile zipFile = ZipFile.builder().setPath(file).get();
6✔
776
        IdeProgressBar pb = this.context.newProgressbarForExtracting(getFileSize(file))) {
7✔
777

778
      final Path root = targetDir.toAbsolutePath().normalize();
4✔
779
      Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
3✔
780

781
      while (entries.hasMoreElements()) {
3✔
782
        ZipArchiveEntry entry = entries.nextElement();
4✔
783
        String entryName = entry.getName();
3✔
784
        Path entryPath = resolveRelativePathSecure(entryName, root);
5✔
785

786
        if (isZipSymlink(entry)) {
3✔
787
          try (InputStream entryStream = zipFile.getInputStream(entry)) {
5✔
788
            // for a symlink entry the file content is the link target path (Unix ZIP convention)
789
            String linkTarget = IOUtils.toString(entryStream, StandardCharsets.UTF_8);
4✔
790
            Path parent = entryPath.getParent();
3✔
791
            resolveRelativePathSecure(parent.resolve(linkTarget).normalize(), root, linkTarget);
9✔
792
            // preserve the raw target so chained links resolve once the bundle is fully extracted
793
            links.add(new PathLink(Path.of(linkTarget), entryPath, PathLinkType.SYMBOLIC_LINK));
12✔
794
            mkdirs(parent);
3✔
795
          }
796
        } else if (entry.isDirectory()) {
3✔
797
          mkdirs(entryPath);
4✔
798
        } else {
799
          mkdirs(entryPath.getParent());
4✔
800
          try (InputStream entryStream = zipFile.getInputStream(entry)) {
4✔
801
            Files.copy(entryStream, entryPath, StandardCopyOption.REPLACE_EXISTING);
10✔
802
          }
803
          onFileCopiedFromZip(entry, entryPath);
4✔
804
        }
805
        pb.stepBy(Math.max(0L, entry.getSize()));
6✔
806
      }
1✔
807

808
      // Phase 2: create all symlinks after regular files and directories have been extracted.
809
      for (PathLink link : links) {
10✔
810
        link(link);
3✔
811
      }
1✔
812
    } catch (IOException e) {
×
813
      throw new IllegalStateException("Failed to extract " + file + " to " + targetDir, e);
×
814
    }
1✔
815
  }
1✔
816

817
  /**
818
   * Returns the Unix file mode stored in the external file attributes of the given ZIP entry.
819
   * <p>
820
   * The ZIP specification stores platform-specific metadata in a 32-bit external-attributes field. When the archive was created on a Unix system the layout
821
   * is:
822
   * <ul>
823
   *   <li>bits 31–16 (upper 16 bits): Unix file mode (same bit layout as {@code stat.st_mode})</li>
824
   *   <li>bits 15–0 (lower 16 bits): MS-DOS attributes (read-only, hidden, …)</li>
825
   * </ul>
826
   * Shifting right by 16 and masking with {@code 0xFFFF} isolates the Unix mode.
827
   *
828
   * @param entry the ZIP entry to read.
829
   * @return the Unix file mode, or {@code 0} if no Unix attributes are present.
830
   */
831
  private static int getZipUnixMode(ZipArchiveEntry entry) {
832

833
    // Right-shift by 16 to move the upper 16 bits (Unix mode) into the lower 16 bits, then
834
    // mask with 0xFFFF to discard any sign-extended bits introduced by the cast.
835
    return (int) ((entry.getExternalAttributes() >> 16) & 0xFFFF);
8✔
836
  }
837

838
  /**
839
   * Returns {@code true} if the given ZIP entry represents a symbolic link.
840
   * <p>
841
   * Unix file modes encode the file type in the top 4 bits (bits 15–12) of the mode word. The possible file-type values are defined in {@code <sys/stat.h>}:
842
   * <ul>
843
   *   <li>{@code 0x8000} – regular file ({@code S_IFREG})</li>
844
   *   <li>{@code 0x4000} – directory ({@code S_IFDIR})</li>
845
   *   <li>{@code 0xA000} – symbolic link ({@code S_IFLNK})</li>
846
   * </ul>
847
   * Masking with {@code 0xF000} isolates those top 4 bits and comparing against {@code 0xA000} identifies symlinks.
848
   *
849
   * @param entry the ZIP entry to test.
850
   * @return {@code true} if the entry is a symbolic link, {@code false} otherwise.
851
   */
852
  private static boolean isZipSymlink(ZipArchiveEntry entry) {
853

854
    // 0xF000 masks the file-type nibble; 0xA000 is the Unix S_IFLNK constant.
855
    return (getZipUnixMode(entry) & 0xF000) == 0xA000;
10✔
856
  }
857

858
  /**
859
   * Applies Unix file permissions stored in a ZIP entry to the extracted file.
860
   * <p>
861
   * Permissions are only applied on non-Windows systems because POSIX permission bits have no equivalent on Windows. If the entry carries no Unix attributes
862
   * (mode is {@code 0}), the call is a no-op.
863
   *
864
   * @param entry the source ZIP entry carrying the Unix mode.
865
   * @param target the extracted file whose permissions should be updated.
866
   */
867
  private void onFileCopiedFromZip(ZipArchiveEntry entry, Path target) {
868

869
    if (!this.context.getSystemInfo().isWindows()) {
5✔
870
      try {
871
        int unixMode = getZipUnixMode(entry);
3✔
872
        if (unixMode != 0) {
2✔
873
          Files.setPosixFilePermissions(target, PathPermissions.of(unixMode).toPosix());
6✔
874
        }
875
      } catch (Exception e) {
×
876
        LOG.error("Failed to transfer zip permissions for {}", target, e);
×
877
      }
1✔
878
    }
879
  }
1✔
880

881
  @Override
882
  public void extractTar(Path file, Path targetDir, TarCompression compression) {
883

884
    extractArchive(file, targetDir, in -> new TarArchiveInputStream(compression.unpack(in)));
13✔
885
  }
1✔
886

887
  @Override
888
  public void extractJar(Path file, Path targetDir) {
889

890
    extractZip(file, targetDir);
4✔
891
  }
1✔
892

893
  /**
894
   * @param permissions The integer as returned by {@link TarArchiveEntry#getMode()} that represents the file permissions of a file on a Unix file system.
895
   * @return A String representing the file permissions. E.g. "rwxrwxr-x" or "rw-rw-r--"
896
   */
897
  public static String generatePermissionString(int permissions) {
898

899
    // Ensure that only the last 9 bits are considered
900
    permissions &= 0b111111111;
4✔
901

902
    StringBuilder permissionStringBuilder = new StringBuilder("rwxrwxrwx");
5✔
903
    for (int i = 0; i < 9; i++) {
7✔
904
      int mask = 1 << i;
4✔
905
      char currentChar = ((permissions & mask) != 0) ? permissionStringBuilder.charAt(8 - i) : '-';
12✔
906
      permissionStringBuilder.setCharAt(8 - i, currentChar);
6✔
907
    }
908

909
    return permissionStringBuilder.toString();
3✔
910
  }
911

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

914
    LOG.info("Extracting TAR file {} to {}", file, targetDir);
5✔
915

916
    final List<PathLink> links = new ArrayList<>();
4✔
917
    try (InputStream is = Files.newInputStream(file);
5✔
918
        ArchiveInputStream<?> ais = unpacker.apply(is);
5✔
919
        IdeProgressBar pb = this.context.newProgressbarForExtracting(getFileSize(file))) {
7✔
920

921
      final Path root = targetDir.toAbsolutePath().normalize();
4✔
922

923
      ArchiveEntry entry = ais.getNextEntry();
3✔
924
      while (entry != null) {
2✔
925
        String entryName = entry.getName();
3✔
926
        Path entryPath = resolveRelativePathSecure(entryName, root);
5✔
927
        PathPermissions permissions = null;
2✔
928
        PathLinkType linkType = null;
2✔
929
        if (entry instanceof TarArchiveEntry tae) {
6!
930
          if (tae.isSymbolicLink()) {
3✔
931
            linkType = PathLinkType.SYMBOLIC_LINK;
3✔
932
          } else if (tae.isLink()) {
3!
933
            linkType = PathLinkType.HARD_LINK;
×
934
          }
935
          if (linkType == null) {
2✔
936
            permissions = PathPermissions.of(tae.getMode());
5✔
937
          } else {
938
            Path parent = entryPath.getParent();
3✔
939
            String sourcePathString = tae.getLinkName();
3✔
940
            Path absoluteSource = resolveRelativePathSecure(parent.resolve(sourcePathString).normalize(), root, sourcePathString);
9✔
941
            // symlink: preserve the raw target so chained links resolve once the bundle is fully extracted.
942
            // hardlink: pass the resolved absolute source - createHardLink requires an existing file.
943
            Path linkSource = linkType == PathLinkType.SYMBOLIC_LINK ? Path.of(sourcePathString) : absoluteSource;
9!
944
            links.add(new PathLink(linkSource, entryPath, linkType));
9✔
945
            mkdirs(parent);
3✔
946
          }
947
        }
948
        if (entry.isDirectory()) {
3✔
949
          mkdirs(entryPath);
4✔
950
        } else if (linkType == null) { // regular file
2✔
951
          mkdirs(entryPath.getParent());
4✔
952
          Files.copy(ais, entryPath, StandardCopyOption.REPLACE_EXISTING);
10✔
953
          // POSIX perms on non-Windows
954
          if (permissions != null) {
2!
955
            setFilePermissions(entryPath, permissions, false);
5✔
956
          }
957
        }
958
        pb.stepBy(Math.max(0L, entry.getSize()));
6✔
959
        entry = ais.getNextEntry();
3✔
960
      }
1✔
961
      // post process links
962
      for (PathLink link : links) {
10✔
963
        link(link);
3✔
964
      }
1✔
965
    } catch (Exception e) {
×
966
      throw new IllegalStateException("Failed to extract " + file + " to " + targetDir, e);
×
967
    }
1✔
968
  }
1✔
969

970
  private Path resolveRelativePathSecure(String entryName, Path root) {
971
    // Handle ZIP entries with absolute paths (e.g. "/bin/java") by converting them to relative paths
972
    if (entryName != null && entryName.startsWith("/")) {
6!
973
      entryName = entryName.substring(1);
×
974
    }
975

976
    Path entryPath = root.resolve(entryName).normalize();
5✔
977
    return resolveRelativePathSecure(entryPath, root, entryName);
6✔
978
  }
979

980
  private Path resolveRelativePathSecure(Path entryPath, Path root, String entryName) {
981

982
    if (!entryPath.startsWith(root)) {
4!
983
      throw new IllegalStateException("Preventing path traversal attack from " + entryName + " to " + entryPath + " leaving " + root);
×
984
    }
985
    return entryPath;
2✔
986
  }
987

988
  @Override
989
  public void extractDmg(Path file, Path targetDir) {
990

991
    LOG.info("Extracting DMG file {} to {}", file, targetDir);
×
992
    assert this.context.getSystemInfo().isMac();
×
993

994
    Path mountPath = this.context.getIdeHome().resolve(IdeContext.FOLDER_UPDATES).resolve(IdeContext.FOLDER_VOLUME);
×
995
    mkdirs(mountPath);
×
996
    ProcessContext pc = this.context.newProcess();
×
997
    pc.executable("hdiutil");
×
998
    pc.addArgs("attach", "-quiet", "-nobrowse", "-mountpoint", mountPath, file);
×
999
    pc.run();
×
1000
    Path appPath = findFirst(mountPath, p -> p.getFileName().toString().endsWith(".app"), false);
×
1001
    if (appPath == null) {
×
1002
      throw new IllegalStateException("Failed to unpack DMG as no MacOS *.app was found in file " + file);
×
1003
    }
1004

1005
    copy(appPath, targetDir, FileCopyMode.COPY_TREE_OVERRIDE_TREE);
×
1006
    pc.addArgs("detach", "-force", mountPath);
×
1007
    pc.run();
×
1008
  }
×
1009

1010
  @Override
1011
  public void extractMsi(Path file, Path targetDir) {
1012

1013
    LOG.info("Extracting MSI file {} to {}", file, targetDir);
×
1014
    this.context.newProcess().executable("msiexec").addArgs("/a", file, "/qn", "TARGETDIR=" + targetDir).run();
×
1015
    // msiexec also creates a copy of the MSI
1016
    Path msiCopy = targetDir.resolve(file.getFileName());
×
1017
    delete(msiCopy);
×
1018
  }
×
1019

1020
  @Override
1021
  public void extractPkg(Path file, Path targetDir) {
1022

1023
    LOG.info("Extracting PKG file {} to {}", file, targetDir);
×
1024
    assert this.context.getSystemInfo().isMac();
×
1025
    Path tmpDirPkg = createTempDir("ide-pkg-");
×
1026
    ProcessContext pc = this.context.newProcess();
×
1027
    pc.executable("xar").addArgs("-C", tmpDirPkg, "-xf", file).run();
×
1028
    Path contentPath = findFirst(tmpDirPkg, p -> p.getFileName().toString().equals("Payload"), true);
×
1029
    extractPkgPayloadWithSystemTar(contentPath, targetDir);
×
1030
    delete(tmpDirPkg);
×
1031
  }
×
1032

1033
  private void extractPkgPayloadWithSystemTar(Path payload, Path targetDir) {
1034

1035
    mkdirs(targetDir);
×
1036
    ProcessContext pc = this.context.newProcess();
×
1037
    pc.executable("/usr/bin/tar");
×
1038
    pc.addArgs("-xf", payload, "-C", targetDir);
×
1039
    pc.run();
×
1040
  }
×
1041

1042
  @Override
1043
  public void compress(Path dir, OutputStream out, String path) {
1044

1045
    String extension = FilenameUtil.getExtension(path);
3✔
1046
    TarCompression tarCompression = TarCompression.of(extension);
3✔
1047
    if (tarCompression != null) {
2!
1048
      compressTar(dir, out, tarCompression);
6✔
1049
    } else if (extension.equals("zip")) {
×
1050
      compressZip(dir, out);
×
1051
    } else {
1052
      throw new IllegalArgumentException("Unsupported extension: " + extension);
×
1053
    }
1054
  }
1✔
1055

1056
  @Override
1057
  public void compressTar(Path dir, OutputStream out, TarCompression tarCompression) {
1058

1059
    switch (tarCompression) {
8!
1060
      case null -> compressTar(dir, out);
×
1061
      case NONE -> compressTar(dir, out);
×
1062
      case GZ -> compressTarGz(dir, out);
5✔
1063
      case BZIP2 -> compressTarBzip2(dir, out);
×
1064
      default -> throw new IllegalArgumentException("Unsupported tar compression: " + tarCompression);
×
1065
    }
1066
  }
1✔
1067

1068
  @Override
1069
  public void compressTarGz(Path dir, OutputStream out) {
1070

1071
    GzipParameters parameters = new GzipParameters();
4✔
1072
    parameters.setModificationTime(0);
3✔
1073
    try (GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(out, parameters)) {
6✔
1074
      compressTarOrThrow(dir, gzOut);
4✔
1075
    } catch (IOException e) {
×
1076
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar.gz file.", e);
×
1077
    }
1✔
1078
  }
1✔
1079

1080
  @Override
1081
  public void compressTarBzip2(Path dir, OutputStream out) {
1082

1083
    try (BZip2CompressorOutputStream bzip2Out = new BZip2CompressorOutputStream(out)) {
×
1084
      compressTarOrThrow(dir, bzip2Out);
×
1085
    } catch (IOException e) {
×
1086
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar.bz2 file.", e);
×
1087
    }
×
1088
  }
×
1089

1090
  @Override
1091
  public void compressTar(Path dir, OutputStream out) {
1092

1093
    try {
1094
      compressTarOrThrow(dir, out);
×
1095
    } catch (IOException e) {
×
1096
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar file.", e);
×
1097
    }
×
1098
  }
×
1099

1100
  private void compressTarOrThrow(Path dir, OutputStream out) throws IOException {
1101

1102
    try (TarArchiveOutputStream tarOut = new TarArchiveOutputStream(out)) {
5✔
1103
      compressRecursive(dir, tarOut, "");
5✔
1104
      tarOut.finish();
2✔
1105
    }
1106
  }
1✔
1107

1108
  @Override
1109
  public void compressZip(Path dir, OutputStream out) {
1110

1111
    try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(out)) {
5✔
1112
      compressRecursive(dir, zipOut, "");
5✔
1113
      zipOut.finish();
2✔
1114
    } catch (IOException e) {
×
1115
      throw new IllegalStateException("Failed to compress directory " + dir + " to zip file.", e);
×
1116
    }
1✔
1117
  }
1✔
1118

1119
  private <E extends ArchiveEntry> void compressRecursive(Path path, ArchiveOutputStream<E> out, String relativePath) {
1120

1121
    try (Stream<Path> childStream = Files.list(path).sorted()) {
4✔
1122
      Iterator<Path> iterator = childStream.iterator();
3✔
1123
      while (iterator.hasNext()) {
3✔
1124
        Path child = iterator.next();
4✔
1125
        String relativeChildPath = relativePath + "/" + child.getFileName().toString();
6✔
1126
        boolean isDirectory = Files.isDirectory(child);
5✔
1127
        E archiveEntry = out.createArchiveEntry(child, relativeChildPath);
7✔
1128
        FileTime none = FileTime.fromMillis(0);
3✔
1129
        if (archiveEntry instanceof TarArchiveEntry tarEntry) {
6✔
1130
          tarEntry.setCreationTime(none);
3✔
1131
          tarEntry.setModTime(none);
3✔
1132
          tarEntry.setLastAccessTime(none);
3✔
1133
          tarEntry.setLastModifiedTime(none);
3✔
1134
          tarEntry.setUserId(0);
3✔
1135
          tarEntry.setUserName("user");
3✔
1136
          tarEntry.setGroupId(0);
3✔
1137
          tarEntry.setGroupName("group");
3✔
1138
          PathPermissions filePermissions = getFilePermissions(child);
4✔
1139
          tarEntry.setMode(filePermissions.toMode());
4✔
1140
        } else if (archiveEntry instanceof ZipArchiveEntry zipEntry) {
7!
1141
          zipEntry.setCreationTime(none);
4✔
1142
          zipEntry.setLastAccessTime(none);
4✔
1143
          zipEntry.setLastModifiedTime(none);
4✔
1144
          zipEntry.setTime(none);
3✔
1145
        }
1146
        out.putArchiveEntry(archiveEntry);
3✔
1147
        if (!isDirectory) {
2✔
1148
          try (InputStream in = Files.newInputStream(child)) {
5✔
1149
            IOUtils.copy(in, out);
4✔
1150
          }
1151
        }
1152
        out.closeArchiveEntry();
2✔
1153
        if (isDirectory) {
2✔
1154
          compressRecursive(child, out, relativeChildPath);
5✔
1155
        }
1156
      }
1✔
1157
    } catch (IOException e) {
×
1158
      throw new IllegalStateException("Failed to compress " + path, e);
×
1159
    }
1✔
1160
  }
1✔
1161

1162
  @Override
1163
  public void delete(Path path) {
1164

1165
    if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
9✔
1166
      LOG.trace("Deleting {} skipped as the path does not exist.", path);
4✔
1167
      return;
1✔
1168
    }
1169
    LOG.debug("Deleting {} ...", path);
4✔
1170
    try {
1171
      if (isLink(path)) {
4✔
1172
        deletePath(path);
4✔
1173
      } else {
1174
        deleteRecursive(path);
3✔
1175
      }
1176
    } catch (IOException e) {
×
1177
      throw new IllegalStateException("Failed to delete " + path, e);
×
1178
    }
1✔
1179
  }
1✔
1180

1181
  private void deleteRecursive(Path path) throws IOException {
1182

1183
    if (Files.isSymbolicLink(path) || isJunction(path)) {
7!
1184
      LOG.trace("Deleting link {} ...", path);
4✔
1185
      Files.delete(path);
2✔
1186
      return;
1✔
1187
    }
1188
    if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) {
9✔
1189
      try (Stream<Path> childStream = Files.list(path)) {
3✔
1190
        Iterator<Path> iterator = childStream.iterator();
3✔
1191
        while (iterator.hasNext()) {
3✔
1192
          Path child = iterator.next();
4✔
1193
          deleteRecursive(child);
3✔
1194
        }
1✔
1195
      }
1196
    }
1197
    deletePath(path);
3✔
1198
  }
1✔
1199

1200
  private boolean isLink(Path path) {
1201

1202
    return Files.isSymbolicLink(path) || isJunction(path);
11!
1203
  }
1204

1205
  private void deletePath(Path path) throws IOException {
1206

1207
    LOG.trace("Deleting {} ...", path);
4✔
1208
    boolean isSetWritable = setWritable(path, true);
5✔
1209
    if (!isSetWritable) {
2✔
1210
      LOG.debug("Couldn't give write access to file: {}", path);
4✔
1211
    }
1212
    Files.delete(path);
2✔
1213
  }
1✔
1214

1215
  @Override
1216
  public Path findFirst(Path dir, Predicate<Path> filter, boolean recursive) {
1217

1218
    try {
1219
      if (!Files.isDirectory(dir)) {
5!
1220
        return null;
×
1221
      }
1222
      return findFirstRecursive(dir, filter, recursive);
6✔
1223
    } catch (IOException e) {
×
1224
      throw new IllegalStateException("Failed to search for file in " + dir, e);
×
1225
    }
1226
  }
1227

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

1230
    List<Path> folders = null;
2✔
1231
    try (Stream<Path> childStream = Files.list(dir)) {
3✔
1232
      Iterator<Path> iterator = childStream.iterator();
3✔
1233
      while (iterator.hasNext()) {
3✔
1234
        Path child = iterator.next();
4✔
1235
        if (filter.test(child)) {
4✔
1236
          return child;
4✔
1237
        } else if (recursive && Files.isDirectory(child)) {
2!
1238
          if (folders == null) {
×
1239
            folders = new ArrayList<>();
×
1240
          }
1241
          folders.add(child);
×
1242
        }
1243
      }
1✔
1244
    }
4!
1245
    if (folders != null) {
2!
1246
      for (Path child : folders) {
×
1247
        Path match = findFirstRecursive(child, filter, recursive);
×
1248
        if (match != null) {
×
1249
          return match;
×
1250
        }
1251
      }
×
1252
    }
1253
    return null;
2✔
1254
  }
1255

1256
  @Override
1257
  public Path findAncestor(Path path, Path baseDir, int subfolderCount) {
1258

1259
    if ((path == null) || (baseDir == null)) {
4!
1260
      LOG.debug("Path should not be null for findAncestor.");
3✔
1261
      return null;
2✔
1262
    }
1263
    if (subfolderCount <= 0) {
2!
1264
      throw new IllegalArgumentException("Subfolder count: " + subfolderCount);
×
1265
    }
1266
    // 1. option relativize
1267
    // 2. recursive getParent
1268
    // 3. loop getParent???
1269
    // 4. getName + getNameCount
1270
    path = path.toAbsolutePath().normalize();
4✔
1271
    baseDir = baseDir.toAbsolutePath().normalize();
4✔
1272
    int directoryNameCount = path.getNameCount();
3✔
1273
    int baseDirNameCount = baseDir.getNameCount();
3✔
1274
    int delta = directoryNameCount - baseDirNameCount - subfolderCount;
6✔
1275
    if (delta < 0) {
2!
1276
      return null;
×
1277
    }
1278
    // ensure directory is a sub-folder of baseDir
1279
    for (int i = 0; i < baseDirNameCount; i++) {
7✔
1280
      if (!path.getName(i).toString().equals(baseDir.getName(i).toString())) {
10✔
1281
        return null;
2✔
1282
      }
1283
    }
1284
    Path result = path;
2✔
1285
    while (delta > 0) {
2✔
1286
      result = result.getParent();
3✔
1287
      delta--;
2✔
1288
    }
1289
    return result;
2✔
1290
  }
1291

1292
  @Override
1293
  public List<Path> listChildrenMapped(Path dir, Function<Path, Path> filter) {
1294

1295
    if (!Files.isDirectory(dir)) {
5✔
1296
      return List.of();
2✔
1297
    }
1298
    List<Path> children = new ArrayList<>();
4✔
1299
    try (Stream<Path> childStream = Files.list(dir)) {
3✔
1300
      Iterator<Path> iterator = childStream.iterator();
3✔
1301
      while (iterator.hasNext()) {
3✔
1302
        Path child = iterator.next();
4✔
1303
        Path filteredChild = filter.apply(child);
5✔
1304
        if (filteredChild != null) {
2✔
1305
          if (filteredChild == child) {
3!
1306
            LOG.trace("Accepted file {}", child);
5✔
1307
          } else {
1308
            LOG.trace("Accepted file {} and mapped to {}", child, filteredChild);
×
1309
          }
1310
          children.add(filteredChild);
5✔
1311
        } else {
1312
          LOG.trace("Ignoring file {} according to filter", child);
4✔
1313
        }
1314
      }
1✔
1315
    } catch (IOException e) {
×
1316
      throw new IllegalStateException("Failed to find children of directory " + dir, e);
×
1317
    }
1✔
1318
    return children;
2✔
1319
  }
1320

1321
  @Override
1322
  public boolean isEmptyDir(Path dir) {
1323

1324
    return listChildren(dir, f -> true).isEmpty();
6✔
1325
  }
1326

1327
  @Override
1328
  public boolean isNonEmptyFile(Path file) {
1329

1330
    if (Files.isRegularFile(file)) {
5✔
1331
      return (getFileSize(file) > 0);
10✔
1332
    }
1333
    return false;
2✔
1334
  }
1335

1336
  private long getFileSize(Path file) {
1337

1338
    try {
1339
      return Files.size(file);
3✔
1340
    } catch (IOException e) {
×
1341
      LOG.warn("Failed to determine size of file {}: {}", file, e.toString(), e);
×
1342
      return 0;
×
1343
    }
1344
  }
1345

1346

1347
  @Override
1348
  public Path findExistingFile(String fileName, List<Path> searchDirs) {
1349

1350
    for (Path dir : searchDirs) {
10!
1351
      Path filePath = dir.resolve(fileName);
4✔
1352
      try {
1353
        if (Files.exists(filePath)) {
5✔
1354
          return filePath;
2✔
1355
        }
1356
      } catch (Exception e) {
×
1357
        throw new IllegalStateException("Unexpected error while checking existence of file " + filePath + " .", e);
×
1358
      }
1✔
1359
    }
1✔
1360
    return null;
×
1361
  }
1362

1363
  @Override
1364
  public boolean setWritable(Path file, boolean writable) {
1365

1366
    if (!Files.exists(file)) {
5✔
1367
      return false;
2✔
1368
    }
1369
    try {
1370
      // POSIX
1371
      PosixFileAttributeView posix = Files.getFileAttributeView(file, PosixFileAttributeView.class);
7✔
1372
      if (posix != null) {
2!
1373
        Set<PosixFilePermission> permissions = new HashSet<>(posix.readAttributes().permissions());
7✔
1374
        boolean changed;
1375
        if (writable) {
2!
1376
          changed = permissions.add(PosixFilePermission.OWNER_WRITE);
5✔
1377
        } else {
1378
          changed = permissions.remove(PosixFilePermission.OWNER_WRITE);
×
1379
        }
1380
        if (changed) {
2!
1381
          posix.setPermissions(permissions);
×
1382
        }
1383
        return true;
2✔
1384
      }
1385

1386
      // Windows
1387
      DosFileAttributeView dos = Files.getFileAttributeView(file, DosFileAttributeView.class);
×
1388
      if (dos != null) {
×
1389
        dos.setReadOnly(!writable);
×
1390
        return true;
×
1391
      }
1392

1393
      LOG.debug("Failed to set writing permission for file {}", file);
×
1394
      return false;
×
1395

1396
    } catch (IOException e) {
×
1397
      LOG.debug("Error occurred when trying to set writing permission for file {}: {}", file, e.toString(), e);
×
1398
      return false;
×
1399
    }
1400
  }
1401

1402
  @Override
1403
  public void makeExecutable(Path path, boolean confirm) {
1404

1405
    if (Files.exists(path)) {
5✔
1406
      if (skipPermissionsIfWindows(path)) {
4!
1407
        return;
×
1408
      }
1409
      PathPermissions existingPermissions = getFilePermissions(path);
4✔
1410
      PathPermissions executablePermissions = existingPermissions.makeExecutable();
3✔
1411
      boolean update = (executablePermissions != existingPermissions);
7✔
1412
      if (update) {
2✔
1413
        if (confirm) {
2!
1414
          boolean yesContinue = this.context.question(
×
1415
              "We want to execute {} but this command seems to lack executable permissions!\n"
1416
                  + "Most probably the tool vendor did forget to add x-flags in the binary release package.\n"
1417
                  + "Before running the command, we suggest to set executable permissions to the file:\n"
1418
                  + "{}\n"
1419
                  + "For security reasons we ask for your confirmation so please check this request.\n"
1420
                  + "Changing permissions from {} to {}.\n"
1421
                  + "Do you confirm to make the command executable before running it?", path.getFileName(), path, existingPermissions, executablePermissions);
×
1422
          if (!yesContinue) {
×
1423
            return;
×
1424
          }
1425
        }
1426
        setFilePermissions(path, executablePermissions, false);
6✔
1427
      } else {
1428
        LOG.trace("Executable flags already present so no need to set them for file {}", path);
4✔
1429
      }
1430
    } else {
1✔
1431
      LOG.warn("Cannot set executable flag on file that does not exist: {}", path);
4✔
1432
    }
1433
  }
1✔
1434

1435
  @Override
1436
  public PathPermissions getFilePermissions(Path path) {
1437

1438
    PathPermissions pathPermissions;
1439
    String info = "";
2✔
1440
    if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
1441
      info = "mocked-";
×
1442
      if (Files.isDirectory(path)) {
×
1443
        pathPermissions = PathPermissions.MODE_RWX_RX_RX;
×
1444
      } else {
1445
        Path parent = path.getParent();
×
1446
        if ((parent != null) && (parent.getFileName().toString().equals("bin"))) {
×
1447
          pathPermissions = PathPermissions.MODE_RWX_RX_RX;
×
1448
        } else {
1449
          pathPermissions = PathPermissions.MODE_RW_R_R;
×
1450
        }
1451
      }
×
1452
    } else {
1453
      Set<PosixFilePermission> permissions;
1454
      try {
1455
        // Read the current file permissions
1456
        permissions = Files.getPosixFilePermissions(path);
5✔
1457
      } catch (IOException e) {
×
1458
        throw new RuntimeException("Failed to get permissions for " + path, e);
×
1459
      }
1✔
1460
      pathPermissions = PathPermissions.of(permissions);
3✔
1461
    }
1462
    LOG.trace("Read {}permissions of {} as {}.", info, path, pathPermissions);
17✔
1463
    return pathPermissions;
2✔
1464
  }
1465

1466
  @Override
1467
  public void setFilePermissions(Path path, PathPermissions permissions, boolean logErrorAndContinue) {
1468

1469
    if (skipPermissionsIfWindows(path)) {
4!
1470
      return;
×
1471
    }
1472
    try {
1473
      LOG.debug("Setting permissions for {} to {}", path, permissions);
5✔
1474
      // Set the new permissions
1475
      Files.setPosixFilePermissions(path, permissions.toPosix());
5✔
1476
    } catch (IOException e) {
×
1477
      String message = "Failed to set permissions to " + permissions + " for path " + path;
×
1478
      if (logErrorAndContinue) {
×
1479
        LOG.warn(message, e);
×
1480
      } else {
1481
        throw new RuntimeException(message, e);
×
1482
      }
1483
    }
1✔
1484
  }
1✔
1485

1486
  private boolean skipPermissionsIfWindows(Path path) {
1487

1488
    if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
1489
      LOG.trace("Windows does not have file permissions hence omitting for {}", path);
×
1490
      return true;
×
1491
    }
1492
    return false;
2✔
1493
  }
1494

1495
  @Override
1496
  public void touch(Path file) {
1497

1498
    if (Files.exists(file)) {
5✔
1499
      try {
1500
        Files.setLastModifiedTime(file, FileTime.fromMillis(System.currentTimeMillis()));
5✔
1501
      } catch (IOException e) {
×
1502
        throw new IllegalStateException("Could not update modification-time of " + file, e);
×
1503
      }
1✔
1504
    } else {
1505
      try {
1506
        Files.createFile(file);
5✔
1507
      } catch (IOException e) {
1✔
1508
        throw new IllegalStateException("Could not create empty file " + file, e);
8✔
1509
      }
1✔
1510
    }
1511
  }
1✔
1512

1513
  @Override
1514
  public String readFileContent(Path file) {
1515

1516
    LOG.trace("Reading content of file from {}", file);
4✔
1517
    if (!Files.exists((file))) {
5✔
1518
      LOG.debug("File {} does not exist", file);
4✔
1519
      return null;
2✔
1520
    }
1521
    try {
1522
      String content = Files.readString(file);
3✔
1523
      LOG.trace("Completed reading {} character(s) from file {}", content.length(), file);
7✔
1524
      return content;
2✔
1525
    } catch (IOException e) {
×
1526
      throw new IllegalStateException("Failed to read file " + file, e);
×
1527
    }
1528
  }
1529

1530
  @Override
1531
  public void writeFileContent(String content, Path file, boolean createParentDir) {
1532

1533
    if (createParentDir) {
2✔
1534
      mkdirs(file.getParent());
4✔
1535
    }
1536
    if (content == null) {
2!
1537
      content = "";
×
1538
    }
1539
    LOG.trace("Writing content with {} character(s) to file {}", content.length(), file);
7✔
1540
    if (Files.exists(file)) {
5✔
1541
      LOG.info("Overriding content of file {}", file);
4✔
1542
    }
1543
    try {
1544
      Files.writeString(file, content);
6✔
1545
      LOG.trace("Wrote content to file {}", file);
4✔
1546
    } catch (IOException e) {
×
1547
      throw new RuntimeException("Failed to write file " + file, e);
×
1548
    }
1✔
1549
  }
1✔
1550

1551
  @Override
1552
  public List<String> readFileLines(Path file) {
1553

1554
    LOG.trace("Reading lines of file from {}", file);
4✔
1555
    if (!Files.exists(file)) {
5✔
1556
      LOG.warn("File {} does not exist", file);
4✔
1557
      return null;
2✔
1558
    }
1559
    try {
1560
      List<String> content = Files.readAllLines(file);
3✔
1561
      LOG.trace("Completed reading {} lines from file {}", content.size(), file);
7✔
1562
      return content;
2✔
1563
    } catch (IOException e) {
×
1564
      throw new IllegalStateException("Failed to read file " + file, e);
×
1565
    }
1566
  }
1567

1568
  @Override
1569
  public void writeFileLines(List<String> content, Path file, boolean createParentDir) {
1570

1571
    if (createParentDir) {
2!
1572
      mkdirs(file.getParent());
×
1573
    }
1574
    if (content == null) {
2!
1575
      content = List.of();
×
1576
    }
1577
    LOG.trace("Writing content with {} lines to file {}", content.size(), file);
7✔
1578
    if (Files.exists(file)) {
5✔
1579
      LOG.debug("Overriding content of file {}", file);
4✔
1580
    }
1581
    try {
1582
      Files.write(file, content);
6✔
1583
      LOG.trace("Wrote lines to file {}", file);
4✔
1584
    } catch (IOException e) {
×
1585
      throw new RuntimeException("Failed to write file " + file, e);
×
1586
    }
1✔
1587
  }
1✔
1588

1589
  @Override
1590
  public void readProperties(Path file, Properties properties) {
1591

1592
    try (Reader reader = Files.newBufferedReader(file)) {
3✔
1593
      properties.load(reader);
3✔
1594
      LOG.debug("Successfully loaded {} properties from {}", properties.size(), file);
7✔
1595
    } catch (IOException e) {
×
1596
      throw new IllegalStateException("Failed to read properties file: " + file, e);
×
1597
    }
1✔
1598
  }
1✔
1599

1600
  @Override
1601
  public void writeProperties(Properties properties, Path file, boolean createParentDir) {
1602

1603
    if (createParentDir) {
2✔
1604
      mkdirs(file.getParent());
4✔
1605
    }
1606
    try (Writer writer = Files.newBufferedWriter(file)) {
5✔
1607
      properties.store(writer, null); // do not get confused - Java still writes a date/time header that cannot be omitted
4✔
1608
      LOG.debug("Successfully saved {} properties to {}", properties.size(), file);
7✔
1609
    } catch (IOException e) {
×
1610
      throw new IllegalStateException("Failed to save properties file during tests.", e);
×
1611
    }
1✔
1612
  }
1✔
1613

1614
  @Override
1615
  public void readIniFile(Path file, IniFile iniFile) {
1616

1617
    if (!Files.exists(file)) {
5✔
1618
      LOG.debug("INI file {} does not exist.", iniFile);
4✔
1619
      return;
1✔
1620
    }
1621
    List<String> iniLines = readFileLines(file);
4✔
1622
    IniSection currentIniSection = iniFile.getInitialSection();
3✔
1623
    for (String line : iniLines) {
10✔
1624
      if (line.trim().startsWith("[")) {
5✔
1625
        currentIniSection = iniFile.getOrCreateSection(line);
5✔
1626
      } else if (line.isBlank() || IniComment.COMMENT_SYMBOLS.contains(line.trim().charAt(0))) {
11✔
1627
        currentIniSection.addComment(line);
4✔
1628
      } else {
1629
        int index = line.indexOf('=');
4✔
1630
        if (index > 0) {
2!
1631
          currentIniSection.setPropertyLine(line);
3✔
1632
        }
1633
      }
1634
    }
1✔
1635
  }
1✔
1636

1637
  @Override
1638
  public void writeIniFile(IniFile iniFile, Path file, boolean createParentDir) {
1639

1640
    String iniString = iniFile.toString();
3✔
1641
    writeFileContent(iniString, file, createParentDir);
5✔
1642
  }
1✔
1643

1644
  @Override
1645
  public Duration getFileAge(Path path) {
1646

1647
    if (Files.exists(path)) {
5✔
1648
      try {
1649
        long currentTime = System.currentTimeMillis();
2✔
1650
        long fileModifiedTime = Files.getLastModifiedTime(path).toMillis();
6✔
1651
        return Duration.ofMillis(currentTime - fileModifiedTime);
5✔
1652
      } catch (IOException e) {
×
1653
        LOG.warn("Could not get modification-time of {}.", path, e);
×
1654
      }
×
1655
    } else {
1656
      LOG.debug("Path {} is missing - skipping modification-time and file age check.", path);
4✔
1657
    }
1658
    return null;
2✔
1659
  }
1660

1661
  @Override
1662
  public boolean isFileAgeRecent(Path path, Duration cacheDuration) {
1663

1664
    Duration age = getFileAge(path);
4✔
1665
    if (age == null) {
2✔
1666
      return false;
2✔
1667
    }
1668
    LOG.debug("The path {} was last updated {} ago and caching duration is {}.", path, age, cacheDuration);
17✔
1669
    return (age.toMillis() <= cacheDuration.toMillis());
10✔
1670
  }
1671
}
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