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

devonfw / IDEasy / 17725971293

15 Sep 2025 07:50AM UTC coverage: 68.674% (+0.001%) from 68.673%
17725971293

push

github

web-flow
#1480: fixed extraction of tar with links (#1481)

3398 of 5415 branches covered (62.75%)

Branch coverage included in aggregate %.

8870 of 12449 relevant lines covered (71.25%)

3.12 hits per line

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

66.73
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.URI;
11
import java.net.http.HttpClient;
12
import java.net.http.HttpClient.Redirect;
13
import java.net.http.HttpClient.Version;
14
import java.net.http.HttpRequest;
15
import java.net.http.HttpRequest.Builder;
16
import java.net.http.HttpResponse;
17
import java.nio.file.FileSystem;
18
import java.nio.file.FileSystemException;
19
import java.nio.file.FileSystems;
20
import java.nio.file.Files;
21
import java.nio.file.LinkOption;
22
import java.nio.file.NoSuchFileException;
23
import java.nio.file.Path;
24
import java.nio.file.StandardCopyOption;
25
import java.nio.file.attribute.BasicFileAttributes;
26
import java.nio.file.attribute.DosFileAttributeView;
27
import java.nio.file.attribute.FileTime;
28
import java.nio.file.attribute.PosixFileAttributeView;
29
import java.nio.file.attribute.PosixFilePermission;
30
import java.security.DigestInputStream;
31
import java.security.MessageDigest;
32
import java.security.NoSuchAlgorithmException;
33
import java.time.Duration;
34
import java.time.LocalDateTime;
35
import java.util.ArrayList;
36
import java.util.HashSet;
37
import java.util.Iterator;
38
import java.util.List;
39
import java.util.Map;
40
import java.util.Properties;
41
import java.util.Set;
42
import java.util.function.Consumer;
43
import java.util.function.Function;
44
import java.util.function.Predicate;
45
import java.util.stream.Stream;
46

47
import org.apache.commons.compress.archivers.ArchiveEntry;
48
import org.apache.commons.compress.archivers.ArchiveInputStream;
49
import org.apache.commons.compress.archivers.ArchiveOutputStream;
50
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
51
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
52
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
53
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
54
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;
55
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
56
import org.apache.commons.io.IOUtils;
57

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

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

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

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

84
  private static final int MODE_RWX_RX_RX = 0755;
85
  private static final int MODE_RW_R_R = 0644;
86

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

89
  private final IdeContext context;
90

91
  /**
92
   * The constructor.
93
   *
94
   * @param context the {@link IdeContext} to use.
95
   */
96
  public FileAccessImpl(IdeContext context) {
97

98
    super();
2✔
99
    this.context = context;
3✔
100
  }
1✔
101

102
  private HttpClient createHttpClient(String url) {
103

104
    return HttpClient.newBuilder().followRedirects(Redirect.ALWAYS).build();
5✔
105
  }
106

107
  @Override
108
  public void download(String url, Path target) {
109

110
    if (this.context.isOffline()) {
4!
111
      throw CliOfflineException.ofDownloadViaUrl(url);
×
112
    }
113
    if (url.startsWith("http")) {
4✔
114
      downloadViaHttp(url, target);
5✔
115
    } else if (url.startsWith("ftp") || url.startsWith("sftp")) {
8!
116
      throw new IllegalArgumentException("Unsupported download URL: " + url);
×
117
    } else {
118
      Path source = Path.of(url);
5✔
119
      if (isFile(source)) {
4!
120
        // network drive
121
        copyFileWithProgressBar(source, target);
5✔
122
      } else {
123
        throw new IllegalArgumentException("Download path does not point to a downloadable file: " + url);
×
124
      }
125
    }
126
  }
1✔
127

128
  private void downloadViaHttp(String url, Path target) {
129
    List<Version> httpProtocols = IdeVariables.HTTP_VERSIONS.get(context);
6✔
130
    Exception lastException = null;
2✔
131
    if (httpProtocols.isEmpty()) {
3!
132
      try {
133
        this.downloadWithHttpVersion(url, target, null);
5✔
134
        return;
1✔
135
      } catch (Exception e) {
×
136
        lastException = e;
×
137
      }
×
138
    } else {
139
      for (Version version : httpProtocols) {
×
140
        try {
141
          this.downloadWithHttpVersion(url, target, version);
×
142
          return;
×
143
        } catch (Exception ex) {
×
144
          lastException = ex;
×
145
        }
146
      }
×
147
    }
148
    throw new IllegalStateException("Failed to download file from URL " + url + " to " + target, lastException);
×
149
  }
150

151
  private void downloadWithHttpVersion(String url, Path target, Version httpVersion) throws Exception {
152

153
    if (httpVersion == null) {
2!
154
      this.context.info("Trying to download {} from {}", target.getFileName(), url);
16✔
155
    } else {
156
      this.context.info("Trying to download: {} with HTTP protocol version: {}", url, httpVersion);
×
157
    }
158
    mkdirs(target.getParent());
4✔
159

160
    Builder builder = HttpRequest.newBuilder()
2✔
161
        .uri(URI.create(url))
2✔
162
        .GET();
2✔
163
    if (httpVersion != null) {
2!
164
      builder.version(httpVersion);
×
165
    }
166
    try (HttpClient client = createHttpClient(url)) {
4✔
167
      HttpRequest request = builder.build();
3✔
168
      HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
5✔
169
      int statusCode = response.statusCode();
3✔
170
      if (statusCode == 200) {
3!
171
        downloadFileWithProgressBar(url, target, response);
6✔
172
      } else {
173
        throw new IllegalStateException("Download failed with status code " + statusCode);
×
174
      }
175
    }
176
  }
1✔
177

178
  /**
179
   * Downloads a file while showing a {@link IdeProgressBar}.
180
   *
181
   * @param url the url to download.
182
   * @param target Path of the target directory.
183
   * @param response the {@link HttpResponse} to use.
184
   */
185
  private void downloadFileWithProgressBar(String url, Path target, HttpResponse<InputStream> response) {
186

187
    long contentLength = response.headers().firstValueAsLong("content-length").orElse(-1);
7✔
188
    informAboutMissingContentLength(contentLength, url);
4✔
189

190
    byte[] data = new byte[1024];
3✔
191
    boolean fileComplete = false;
2✔
192
    int count;
193

194
    try (InputStream body = response.body();
4✔
195
        FileOutputStream fileOutput = new FileOutputStream(target.toFile());
6✔
196
        BufferedOutputStream bufferedOut = new BufferedOutputStream(fileOutput, data.length);
7✔
197
        IdeProgressBar pb = this.context.newProgressBarForDownload(contentLength)) {
5✔
198
      while (!fileComplete) {
2✔
199
        count = body.read(data);
4✔
200
        if (count <= 0) {
2✔
201
          fileComplete = true;
3✔
202
        } else {
203
          bufferedOut.write(data, 0, count);
5✔
204
          pb.stepBy(count);
5✔
205
        }
206
      }
207

208
    } catch (Exception e) {
×
209
      throw new RuntimeException(e);
×
210
    }
1✔
211
  }
1✔
212

213
  private void copyFileWithProgressBar(Path source, Path target) {
214

215
    long size = getFileSize(source);
4✔
216
    if (size < 100_000) {
4✔
217
      copy(source, target, FileCopyMode.COPY_FILE_TO_TARGET_OVERRIDE);
5✔
218
      return;
1✔
219
    }
220
    try (InputStream in = Files.newInputStream(source);
5✔
221
        OutputStream out = Files.newOutputStream(target)) {
5✔
222
      byte[] buf = new byte[1024];
3✔
223
      try (IdeProgressBar pb = this.context.newProgressbarForCopying(size)) {
5✔
224
        int readBytes;
225
        while ((readBytes = in.read(buf)) > 0) {
6✔
226
          out.write(buf, 0, readBytes);
5✔
227
          pb.stepBy(readBytes);
5✔
228
        }
229
      } catch (Exception e) {
×
230
        throw new RuntimeException(e);
×
231
      }
1✔
232
    } catch (IOException e) {
×
233
      throw new RuntimeException("Failed to copy from " + source + " to " + target, e);
×
234
    }
1✔
235
  }
1✔
236

237
  private void informAboutMissingContentLength(long contentLength, String url) {
238

239
    if (contentLength < 0) {
4✔
240
      this.context.warning("Content-Length was not provided by download from {}", url);
10✔
241
    }
242
  }
1✔
243

244
  @Override
245
  public void mkdirs(Path directory) {
246

247
    if (Files.isDirectory(directory)) {
5✔
248
      return;
1✔
249
    }
250
    this.context.trace("Creating directory {}", directory);
10✔
251
    try {
252
      Files.createDirectories(directory);
5✔
253
    } catch (IOException e) {
×
254
      throw new IllegalStateException("Failed to create directory " + directory, e);
×
255
    }
1✔
256
  }
1✔
257

258
  @Override
259
  public boolean isFile(Path file) {
260

261
    if (!Files.exists(file)) {
5!
262
      this.context.trace("File {} does not exist", file);
×
263
      return false;
×
264
    }
265
    if (Files.isDirectory(file)) {
5!
266
      this.context.trace("Path {} is a directory but a regular file was expected", file);
×
267
      return false;
×
268
    }
269
    return true;
2✔
270
  }
271

272
  @Override
273
  public boolean isExpectedFolder(Path folder) {
274

275
    if (Files.isDirectory(folder)) {
5✔
276
      return true;
2✔
277
    }
278
    this.context.warning("Expected folder was not found at {}", folder);
10✔
279
    return false;
2✔
280
  }
281

282
  @Override
283
  public String checksum(Path file, String hashAlgorithm) {
284

285
    MessageDigest md;
286
    try {
287
      md = MessageDigest.getInstance(hashAlgorithm);
×
288
    } catch (NoSuchAlgorithmException e) {
×
289
      throw new IllegalStateException("No such hash algorithm " + hashAlgorithm, e);
×
290
    }
×
291
    byte[] buffer = new byte[1024];
×
292
    try (InputStream is = Files.newInputStream(file); DigestInputStream dis = new DigestInputStream(is, md)) {
×
293
      int read = 0;
×
294
      while (read >= 0) {
×
295
        read = dis.read(buffer);
×
296
      }
297
    } catch (Exception e) {
×
298
      throw new IllegalStateException("Failed to read and hash file " + file, e);
×
299
    }
×
300
    byte[] digestBytes = md.digest();
×
301
    return HexUtil.toHexString(digestBytes);
×
302
  }
303

304
  @Override
305
  public boolean isJunction(Path path) {
306

307
    if (!SystemInfoImpl.INSTANCE.isWindows()) {
3!
308
      return false;
2✔
309
    }
310
    try {
311
      BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
×
312
      return attr.isOther() && attr.isDirectory();
×
313
    } catch (NoSuchFileException e) {
×
314
      return false; // file doesn't exist
×
315
    } catch (IOException e) {
×
316
      // errors in reading the attributes of the file
317
      throw new IllegalStateException("An unexpected error occurred whilst checking if the file: " + path + " is a junction", e);
×
318
    }
319
  }
320

321
  @Override
322
  public Path backup(Path fileOrFolder) {
323

324
    if ((fileOrFolder != null) && (Files.isSymbolicLink(fileOrFolder) || isJunction(fileOrFolder))) {
9!
325
      delete(fileOrFolder);
4✔
326
    } else if ((fileOrFolder != null) && Files.exists(fileOrFolder)) {
7!
327
      LocalDateTime now = LocalDateTime.now();
2✔
328
      String date = DateTimeUtil.formatDate(now, true);
4✔
329
      String time = DateTimeUtil.formatTime(now);
3✔
330
      String filename = fileOrFolder.getFileName().toString();
4✔
331
      Path backupPath = this.context.getIdeHome().resolve(IdeContext.FOLDER_BACKUPS).resolve(date).resolve(time + "_" + filename);
12✔
332
      backupPath = appendParentPath(backupPath, fileOrFolder.getParent(), 2);
6✔
333
      mkdirs(backupPath);
3✔
334
      Path target = backupPath.resolve(filename);
4✔
335
      this.context.info("Creating backup by moving {} to {}", fileOrFolder, target);
14✔
336
      move(fileOrFolder, target);
6✔
337
      return target;
2✔
338
    } else {
339
      this.context.trace("Backup of {} skipped as the path does not exist.", fileOrFolder);
10✔
340
    }
341
    return fileOrFolder;
2✔
342
  }
343

344
  private static Path appendParentPath(Path path, Path parent, int max) {
345

346
    if ((parent == null) || (max <= 0)) {
4!
347
      return path;
2✔
348
    }
349
    return appendParentPath(path, parent.getParent(), max - 1).resolve(parent.getFileName());
11✔
350
  }
351

352
  @Override
353
  public void move(Path source, Path targetDir, StandardCopyOption... copyOptions) {
354

355
    this.context.trace("Moving {} to {}", source, targetDir);
14✔
356
    try {
357
      Files.move(source, targetDir, copyOptions);
5✔
358
    } catch (IOException e) {
×
359
      String fileType = Files.isSymbolicLink(source) ? "symlink" : isJunction(source) ? "junction" : Files.isDirectory(source) ? "directory" : "file";
×
360
      String message = "Failed to move " + fileType + ": " + source + " to " + targetDir + ".";
×
361
      if (this.context.getSystemInfo().isWindows()) {
×
362
        message = message + "\n" + WINDOWS_FILE_LOCK_WARNING;
×
363
      }
364
      throw new IllegalStateException(message, e);
×
365
    }
1✔
366
  }
1✔
367

368
  @Override
369
  public void copy(Path source, Path target, FileCopyMode mode, PathCopyListener listener) {
370

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

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

415
    if (Files.isDirectory(source)) {
5✔
416
      mkdirs(target);
3✔
417
      try (Stream<Path> childStream = Files.list(source)) {
3✔
418
        Iterator<Path> iterator = childStream.iterator();
3✔
419
        while (iterator.hasNext()) {
3✔
420
          Path child = iterator.next();
4✔
421
          copyRecursive(child, target.resolve(child.getFileName().toString()), mode, listener);
10✔
422
        }
1✔
423
      }
424
      listener.onCopy(source, target, true);
6✔
425
    } else if (Files.exists(source)) {
5!
426
      if (mode.isOverride()) {
3✔
427
        delete(target);
3✔
428
      }
429
      this.context.trace("Starting to {} {} to {}", mode.getOperation(), source, target);
19✔
430
      Files.copy(source, target);
6✔
431
      listener.onCopy(source, target, false);
6✔
432
    } else {
433
      throw new IOException("Path " + source + " does not exist.");
×
434
    }
435
  }
1✔
436

437
  /**
438
   * 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
439
   * {@link Path} that is neither a symbolic link nor a Windows junction.
440
   *
441
   * @param path the {@link Path} to delete.
442
   */
443
  private void deleteLinkIfExists(Path path) {
444

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

448
    assert !(isSymlink && isJunction);
5!
449

450
    if (isJunction || isSymlink) {
4!
451
      this.context.info("Deleting previous " + (isJunction ? "junction" : "symlink") + " at " + path);
9!
452
      try {
453
        Files.delete(path);
2✔
454
      } catch (IOException e) {
×
455
        throw new IllegalStateException("Failed to delete link at " + path, e);
×
456
      }
1✔
457
    }
458
  }
1✔
459

460
  /**
461
   * Adapts the given {@link Path} to be relative or absolute depending on the given {@code relative} flag. Additionally, {@link Path#toRealPath(LinkOption...)}
462
   * is applied to {@code target}.
463
   *
464
   * @param target the {@link Path} the link should point to and that is to be adapted.
465
   * @param link the {@link Path} to the link. It is used to calculate the relative path to the {@code target} if {@code relative} is set to {@code true}.
466
   * @param relative the {@code relative} flag.
467
   * @return the adapted {@link Path}.
468
   * @see #symlink(Path, Path, boolean)
469
   */
470
  private Path adaptPath(Path target, Path link, boolean relative) {
471

472
    if (!target.isAbsolute()) {
3✔
473
      target = link.resolveSibling(target);
4✔
474
    }
475
    try {
476
      target = target.toRealPath(LinkOption.NOFOLLOW_LINKS); // to transform ../d1/../d2 to ../d2
9✔
477
    } catch (IOException e) {
×
478
      throw new RuntimeException("Failed to get real path of " + target, e);
×
479
    }
1✔
480
    if (relative) {
2✔
481
      target = link.getParent().relativize(target);
5✔
482
      // to make relative links like this work: dir/link -> dir
483
      target = (target.toString().isEmpty()) ? Path.of(".") : target;
11✔
484
    }
485
    return target;
2✔
486
  }
487

488
  /**
489
   * Creates a Windows link using mklink at {@code link} pointing to {@code target}.
490
   *
491
   * @param target the {@link Path} the link will point to.
492
   * @param link the {@link Path} where to create the link.
493
   * @param type the {@link PathLinkType}.
494
   */
495
  private void mklinkOnWindows(Path target, Path link, PathLinkType type) {
496

497
    this.context.trace("Creating a Windows link at {} pointing to {}", link, target);
×
498
    ProcessResult result = this.context.newProcess().executable("cmd").addArgs("/c", "mklink", type.getMklinkOption(), link.toString(), target.toString())
×
499
        .run(ProcessMode.DEFAULT);
×
500
    result.failOnError();
×
501
  }
×
502

503
  @Override
504
  public void link(Path target, Path link, boolean relative, PathLinkType type) {
505

506
    final Path finalTarget;
507
    try {
508
      finalTarget = adaptPath(target, link, relative);
6✔
509
    } catch (Exception e) {
×
510
      throw new IllegalStateException("Failed to adapt target (" + target + ") for link (" + link + ") and relative (" + relative + ")", e);
×
511
    }
1✔
512
    String relativeOrAbsolute = finalTarget.isAbsolute() ? "absolute" : "relative";
7✔
513
    this.context.debug("Creating {} {} at {} pointing to {}", relativeOrAbsolute, type, link, finalTarget);
22✔
514
    deleteLinkIfExists(link);
3✔
515
    try {
516
      if (type == PathLinkType.SYMBOLIC_LINK) {
3!
517
        Files.createSymbolicLink(link, finalTarget);
7✔
518
      } else if (type == PathLinkType.HARD_LINK) {
×
519
        Files.createLink(link, finalTarget);
×
520
      } else {
521
        throw new IllegalStateException("" + type);
×
522
      }
523
    } catch (FileSystemException e) {
×
524
      if (SystemInfoImpl.INSTANCE.isWindows()) {
×
525
        this.context.info(
×
526
            "Due to lack of permissions, Microsoft's mklink with junction had to be used to create a Symlink. See\n"
527
                + "https://github.com/devonfw/IDEasy/blob/main/documentation/symlink.adoc for further details. Error was: "
528
                + e.getMessage());
×
529
        mklinkOnWindows(finalTarget, link, type);
×
530
      } else {
531
        throw new RuntimeException(e);
×
532
      }
533
    } catch (IOException e) {
×
534
      throw new IllegalStateException(
×
535
          "Failed to create a " + relativeOrAbsolute + " " + type + " at " + link + " pointing to " + target, e);
536
    }
1✔
537
  }
1✔
538

539
  @Override
540
  public Path toRealPath(Path path) {
541

542
    return toRealPath(path, true);
5✔
543
  }
544

545
  @Override
546
  public Path toCanonicalPath(Path path) {
547

548
    return toRealPath(path, false);
5✔
549
  }
550

551
  private Path toRealPath(Path path, boolean resolveLinks) {
552

553
    try {
554
      Path realPath;
555
      if (resolveLinks) {
2✔
556
        realPath = path.toRealPath();
6✔
557
      } else {
558
        realPath = path.toRealPath(LinkOption.NOFOLLOW_LINKS);
9✔
559
      }
560
      if (!realPath.equals(path)) {
4✔
561
        this.context.trace("Resolved path {} to {}", path, realPath);
14✔
562
      }
563
      return realPath;
2✔
564
    } catch (IOException e) {
×
565
      throw new IllegalStateException("Failed to get real path for " + path, e);
×
566
    }
567
  }
568

569
  @Override
570
  public Path createTempDir(String name) {
571

572
    try {
573
      Path tmp = this.context.getTempPath();
4✔
574
      Path tempDir = tmp.resolve(name);
4✔
575
      int tries = 1;
2✔
576
      while (Files.exists(tempDir)) {
5!
577
        long id = System.nanoTime() & 0xFFFF;
×
578
        tempDir = tmp.resolve(name + "-" + id);
×
579
        tries++;
×
580
        if (tries > 200) {
×
581
          throw new IOException("Unable to create unique name!");
×
582
        }
583
      }
×
584
      return Files.createDirectory(tempDir);
5✔
585
    } catch (IOException e) {
×
586
      throw new IllegalStateException("Failed to create temporary directory with prefix '" + name + "'!", e);
×
587
    }
588
  }
589

590
  @Override
591
  public void extract(Path archiveFile, Path targetDir, Consumer<Path> postExtractHook, boolean extract) {
592

593
    if (Files.isDirectory(archiveFile)) {
5✔
594
      this.context.warning("Found directory for download at {} hence copying without extraction!", archiveFile);
10✔
595
      copy(archiveFile, targetDir, FileCopyMode.COPY_TREE_CONTENT);
5✔
596
      postExtractHook(postExtractHook, targetDir);
4✔
597
      return;
1✔
598
    } else if (!extract) {
2✔
599
      mkdirs(targetDir);
3✔
600
      move(archiveFile, targetDir.resolve(archiveFile.getFileName()));
9✔
601
      return;
1✔
602
    }
603
    Path tmpDir = createTempDir("extract-" + archiveFile.getFileName());
7✔
604
    this.context.trace("Trying to extract the downloaded file {} to {} and move it to {}.", archiveFile, tmpDir, targetDir);
18✔
605
    String filename = archiveFile.getFileName().toString();
4✔
606
    TarCompression tarCompression = TarCompression.of(filename);
3✔
607
    if (tarCompression != null) {
2✔
608
      extractTar(archiveFile, tmpDir, tarCompression);
6✔
609
    } else {
610
      String extension = FilenameUtil.getExtension(filename);
3✔
611
      if (extension == null) {
2!
612
        throw new IllegalStateException("Unknown archive format without extension - can not extract " + archiveFile);
×
613
      } else {
614
        this.context.trace("Determined file extension {}", extension);
10✔
615
      }
616
      switch (extension) {
8!
617
        case "zip" -> extractZip(archiveFile, tmpDir);
×
618
        case "jar" -> extractJar(archiveFile, tmpDir);
5✔
619
        case "dmg" -> extractDmg(archiveFile, tmpDir);
×
620
        case "msi" -> extractMsi(archiveFile, tmpDir);
×
621
        case "pkg" -> extractPkg(archiveFile, tmpDir);
×
622
        default -> throw new IllegalStateException("Unknown archive format " + extension + ". Can not extract " + archiveFile);
×
623
      }
624
    }
625
    Path properInstallDir = getProperInstallationSubDirOf(tmpDir, archiveFile);
5✔
626
    postExtractHook(postExtractHook, properInstallDir);
4✔
627
    move(properInstallDir, targetDir);
6✔
628
    delete(tmpDir);
3✔
629
  }
1✔
630

631
  private void postExtractHook(Consumer<Path> postExtractHook, Path properInstallDir) {
632

633
    if (postExtractHook != null) {
2✔
634
      postExtractHook.accept(properInstallDir);
3✔
635
    }
636
  }
1✔
637

638
  /**
639
   * @param path the {@link Path} to start the recursive search from.
640
   * @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
641
   *     item in their respective directory and {@code s} is not named "bin".
642
   */
643
  private Path getProperInstallationSubDirOf(Path path, Path archiveFile) {
644

645
    try (Stream<Path> stream = Files.list(path)) {
3✔
646
      Path[] subFiles = stream.toArray(Path[]::new);
8✔
647
      if (subFiles.length == 0) {
3!
648
        throw new CliException("The downloaded package " + archiveFile + " seems to be empty as you can check in the extracted folder " + path);
×
649
      } else if (subFiles.length == 1) {
4✔
650
        String filename = subFiles[0].getFileName().toString();
6✔
651
        if (!filename.equals(IdeContext.FOLDER_BIN) && !filename.equals(IdeContext.FOLDER_CONTENTS) && !filename.endsWith(".app") && Files.isDirectory(
4!
652
            subFiles[0])) {
653
          return getProperInstallationSubDirOf(subFiles[0], archiveFile);
×
654
        }
655
      }
656
      return path;
4✔
657
    } catch (IOException e) {
×
658
      throw new IllegalStateException("Failed to get sub-files of " + path);
×
659
    }
660
  }
661

662
  @Override
663
  public void extractZip(Path file, Path targetDir) {
664

665
    this.context.info("Extracting ZIP file {} to {}", file, targetDir);
14✔
666
    URI uri = URI.create("jar:" + file.toUri());
6✔
667
    try (FileSystem fs = FileSystems.newFileSystem(uri, FS_ENV)) {
4✔
668
      long size = 0;
2✔
669
      for (Path root : fs.getRootDirectories()) {
11✔
670
        size += getFileSizeRecursive(root);
6✔
671
      }
1✔
672
      try (final IdeProgressBar progressBar = this.context.newProgressbarForExtracting(size)) {
5✔
673
        for (Path root : fs.getRootDirectories()) {
11✔
674
          copy(root, targetDir, FileCopyMode.EXTRACT, (s, t, d) -> onFileCopiedFromZip(s, t, d, progressBar));
15✔
675
        }
1✔
676
      }
677
    } catch (IOException e) {
×
678
      throw new IllegalStateException("Failed to extract " + file + " to " + targetDir, e);
×
679
    }
1✔
680
  }
1✔
681

682
  @SuppressWarnings("unchecked")
683
  private void onFileCopiedFromZip(Path source, Path target, boolean directory, IdeProgressBar progressBar) {
684

685
    if (directory) {
2✔
686
      return;
1✔
687
    }
688
    if (!context.getSystemInfo().isWindows()) {
5✔
689
      try {
690
        Object attribute = Files.getAttribute(source, "zip:permissions");
6✔
691
        if (attribute instanceof Set<?> permissionSet) {
6✔
692
          Files.setPosixFilePermissions(target, (Set<PosixFilePermission>) permissionSet);
4✔
693
        }
694
      } catch (Exception e) {
×
695
        context.error(e, "Failed to transfer zip permissions for {}", target);
×
696
      }
1✔
697
    }
698
    progressBar.stepBy(getFileSize(target));
5✔
699
  }
1✔
700

701
  @Override
702
  public void extractTar(Path file, Path targetDir, TarCompression compression) {
703

704
    extractArchive(file, targetDir, in -> new TarArchiveInputStream(compression.unpack(in)));
13✔
705
  }
1✔
706

707
  @Override
708
  public void extractJar(Path file, Path targetDir) {
709

710
    extractZip(file, targetDir);
4✔
711
  }
1✔
712

713
  /**
714
   * @param permissions The integer as returned by {@link TarArchiveEntry#getMode()} that represents the file permissions of a file on a Unix file system.
715
   * @return A String representing the file permissions. E.g. "rwxrwxr-x" or "rw-rw-r--"
716
   */
717
  public static String generatePermissionString(int permissions) {
718

719
    // Ensure that only the last 9 bits are considered
720
    permissions &= 0b111111111;
4✔
721

722
    StringBuilder permissionStringBuilder = new StringBuilder("rwxrwxrwx");
5✔
723
    for (int i = 0; i < 9; i++) {
7✔
724
      int mask = 1 << i;
4✔
725
      char currentChar = ((permissions & mask) != 0) ? permissionStringBuilder.charAt(8 - i) : '-';
12✔
726
      permissionStringBuilder.setCharAt(8 - i, currentChar);
6✔
727
    }
728

729
    return permissionStringBuilder.toString();
3✔
730
  }
731

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

734
    this.context.info("Extracting TAR file {} to {}", file, targetDir);
14✔
735

736
    final List<PathLink> links = new ArrayList<>();
4✔
737
    try (InputStream is = Files.newInputStream(file);
5✔
738
        ArchiveInputStream<?> ais = unpacker.apply(is);
5✔
739
        IdeProgressBar pb = this.context.newProgressbarForExtracting(getFileSize(file))) {
7✔
740

741
      final boolean isTar = (ais instanceof TarArchiveInputStream);
3✔
742
      final boolean isWindows = this.context.getSystemInfo().isWindows();
5✔
743
      final Path root = targetDir.toAbsolutePath().normalize();
4✔
744

745
      ArchiveEntry entry = ais.getNextEntry();
3✔
746
      while (entry != null) {
2✔
747
        String entryName = entry.getName();
3✔
748
        Path entryPath = resolveRelativePathSecure(entryName, root);
5✔
749
        PathPermissions permissions = null;
2✔
750
        PathLinkType linkType = null;
2✔
751
        if (entry instanceof TarArchiveEntry tae) {
6!
752
          if (tae.isSymbolicLink()) {
3!
753
            linkType = PathLinkType.SYMBOLIC_LINK;
×
754
          } else if (tae.isLink()) {
3!
755
            linkType = PathLinkType.HARD_LINK;
×
756
          }
757
          if (linkType == null) {
2!
758
            permissions = PathPermissions.of(tae.getMode());
5✔
759
          } else {
760
            Path parent = entryPath.getParent();
×
761
            String linkName = tae.getLinkName();
×
762
            Path linkTarget = parent.resolve(linkName).normalize();
×
763
            Path target = resolveRelativePathSecure(linkTarget, root, linkName);
×
764
            links.add(new PathLink(entryPath, target, linkType));
×
765
            mkdirs(parent);
×
766
          }
767
        }
768
        if (entry.isDirectory()) {
3✔
769
          mkdirs(entryPath);
4✔
770
        } else if (linkType == null) { // regular file
2!
771
          mkdirs(entryPath.getParent());
4✔
772
          Files.copy(ais, entryPath, StandardCopyOption.REPLACE_EXISTING);
10✔
773
          // POSIX perms on non-Windows
774
          if (!isWindows && (permissions != null)) {
4!
775
            setFilePermissions(entryPath, permissions, false);
5✔
776
          }
777
        }
778
        pb.stepBy(Math.max(0L, entry.getSize()));
6✔
779
        entry = ais.getNextEntry();
3✔
780
      }
1✔
781
      // post process links
782
      for (PathLink link : links) {
6!
783
        link(link);
×
784
      }
×
785
    } catch (Exception e) {
×
786
      throw new IllegalStateException("Failed to extract " + file + " to " + targetDir, e);
×
787
    }
1✔
788
  }
1✔
789

790
  private Path resolveRelativePathSecure(String entryName, Path root) {
791

792
    Path entryPath = root.resolve(entryName).normalize();
5✔
793
    return resolveRelativePathSecure(entryPath, root, entryName);
6✔
794
  }
795

796
  private Path resolveRelativePathSecure(Path entryPath, Path root, String entryName) {
797

798
    if (!entryPath.startsWith(root)) {
4!
799
      throw new IllegalStateException("Preventing path traversal attack from " + entryName + " to " + entryPath + " leaving " + root);
×
800
    }
801
    return entryPath;
2✔
802
  }
803

804

805
  @Override
806
  public void extractDmg(Path file, Path targetDir) {
807

808
    this.context.info("Extracting DMG file {} to {}", file, targetDir);
×
809
    assert this.context.getSystemInfo().isMac();
×
810

811
    Path mountPath = this.context.getIdeHome().resolve(IdeContext.FOLDER_UPDATES).resolve(IdeContext.FOLDER_VOLUME);
×
812
    mkdirs(mountPath);
×
813
    ProcessContext pc = this.context.newProcess();
×
814
    pc.executable("hdiutil");
×
815
    pc.addArgs("attach", "-quiet", "-nobrowse", "-mountpoint", mountPath, file);
×
816
    pc.run();
×
817
    Path appPath = findFirst(mountPath, p -> p.getFileName().toString().endsWith(".app"), false);
×
818
    if (appPath == null) {
×
819
      throw new IllegalStateException("Failed to unpack DMG as no MacOS *.app was found in file " + file);
×
820
    }
821

822
    copy(appPath, targetDir, FileCopyMode.COPY_TREE_OVERRIDE_TREE);
×
823
    pc.addArgs("detach", "-force", mountPath);
×
824
    pc.run();
×
825
  }
×
826

827
  @Override
828
  public void extractMsi(Path file, Path targetDir) {
829

830
    this.context.info("Extracting MSI file {} to {}", file, targetDir);
×
831
    this.context.newProcess().executable("msiexec").addArgs("/a", file, "/qn", "TARGETDIR=" + targetDir).run();
×
832
    // msiexec also creates a copy of the MSI
833
    Path msiCopy = targetDir.resolve(file.getFileName());
×
834
    delete(msiCopy);
×
835
  }
×
836

837
  @Override
838
  public void extractPkg(Path file, Path targetDir) {
839

840
    this.context.info("Extracting PKG file {} to {}", file, targetDir);
×
841
    Path tmpDirPkg = createTempDir("ide-pkg-");
×
842
    ProcessContext pc = this.context.newProcess();
×
843
    // we might also be able to use cpio from commons-compression instead of external xar...
844
    pc.executable("xar").addArgs("-C", tmpDirPkg, "-xf", file).run();
×
845
    Path contentPath = findFirst(tmpDirPkg, p -> p.getFileName().toString().equals("Payload"), true);
×
846
    extractTar(contentPath, targetDir, TarCompression.GZ);
×
847
    delete(tmpDirPkg);
×
848
  }
×
849

850
  @Override
851
  public void compress(Path dir, OutputStream out, String format) {
852

853
    String extension = FilenameUtil.getExtension(format);
3✔
854
    TarCompression tarCompression = TarCompression.of(extension);
3✔
855
    if (tarCompression != null) {
2!
856
      compressTar(dir, out, tarCompression);
6✔
857
    } else if (extension.equals("zip")) {
×
858
      compressZip(dir, out);
×
859
    } else {
860
      throw new IllegalArgumentException("Unsupported extension: " + extension);
×
861
    }
862
  }
1✔
863

864
  @Override
865
  public void compressTar(Path dir, OutputStream out, TarCompression tarCompression) {
866
    switch (tarCompression) {
8!
867
      case null -> compressTar(dir, out);
×
868
      case NONE -> compressTar(dir, out);
×
869
      case GZ -> compressTarGz(dir, out);
5✔
870
      case BZIP2 -> compressTarBzip2(dir, out);
×
871
      default -> throw new IllegalArgumentException("Unsupported tar compression: " + tarCompression);
×
872
    }
873
  }
1✔
874

875
  @Override
876
  public void compressTarGz(Path dir, OutputStream out) {
877
    try (GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(out)) {
5✔
878
      compressTarOrThrow(dir, gzOut);
4✔
879
    } catch (IOException e) {
×
880
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar.gz file.", e);
×
881
    }
1✔
882
  }
1✔
883

884
  @Override
885
  public void compressTarBzip2(Path dir, OutputStream out) {
886
    try (BZip2CompressorOutputStream bzip2Out = new BZip2CompressorOutputStream(out)) {
×
887
      compressTarOrThrow(dir, bzip2Out);
×
888
    } catch (IOException e) {
×
889
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar.bz2 file.", e);
×
890
    }
×
891
  }
×
892

893
  @Override
894
  public void compressTar(Path dir, OutputStream out) {
895
    try {
896
      compressTarOrThrow(dir, out);
×
897
    } catch (IOException e) {
×
898
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar file.", e);
×
899
    }
×
900
  }
×
901

902
  private void compressTarOrThrow(Path dir, OutputStream out) throws IOException {
903
    try (TarArchiveOutputStream tarOut = new TarArchiveOutputStream(out)) {
5✔
904
      compressRecursive(dir, tarOut, "");
5✔
905
      tarOut.finish();
2✔
906
    }
907
  }
1✔
908

909
  @Override
910
  public void compressZip(Path dir, OutputStream out) {
911
    try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(out)) {
×
912
      compressRecursive(dir, zipOut, "");
×
913
      zipOut.finish();
×
914
    } catch (IOException e) {
×
915
      throw new IllegalStateException("Failed to compress directory " + dir + " to zip file.", e);
×
916
    }
×
917
  }
×
918

919
  private <E extends ArchiveEntry> void compressRecursive(Path path, ArchiveOutputStream<E> out, String relativePath) {
920
    try (Stream<Path> childStream = Files.list(path)) {
3✔
921
      Iterator<Path> iterator = childStream.iterator();
3✔
922
      while (iterator.hasNext()) {
3✔
923
        Path child = iterator.next();
4✔
924
        String relativeChildPath = relativePath + "/" + child.getFileName().toString();
6✔
925
        boolean isDirectory = Files.isDirectory(child);
5✔
926
        E archiveEntry = out.createArchiveEntry(child, relativeChildPath);
7✔
927
        if (archiveEntry instanceof TarArchiveEntry tarEntry) {
6!
928
          FileTime none = FileTime.fromMillis(0);
3✔
929
          tarEntry.setCreationTime(none);
3✔
930
          tarEntry.setModTime(none);
3✔
931
          tarEntry.setLastAccessTime(none);
3✔
932
          tarEntry.setLastModifiedTime(none);
3✔
933
          tarEntry.setUserId(0);
3✔
934
          tarEntry.setUserName("user");
3✔
935
          tarEntry.setGroupId(0);
3✔
936
          tarEntry.setGroupName("group");
3✔
937
          if (isDirectory) {
2✔
938
            tarEntry.setMode(MODE_RWX_RX_RX);
4✔
939
          } else {
940
            if (relativePath.endsWith("bin")) {
4✔
941
              tarEntry.setMode(MODE_RWX_RX_RX);
4✔
942
            } else {
943
              tarEntry.setMode(MODE_RW_R_R);
3✔
944
            }
945
          }
946
        }
947
        out.putArchiveEntry(archiveEntry);
3✔
948
        if (!isDirectory) {
2✔
949
          try (InputStream in = Files.newInputStream(child)) {
5✔
950
            IOUtils.copy(in, out);
4✔
951
          }
952
        }
953
        out.closeArchiveEntry();
2✔
954
        if (isDirectory) {
2✔
955
          compressRecursive(child, out, relativeChildPath);
5✔
956
        }
957
      }
1✔
958
    } catch (IOException e) {
×
959
      throw new IllegalStateException("Failed to compress " + path, e);
×
960
    }
1✔
961
  }
1✔
962

963
  @Override
964
  public void delete(Path path) {
965

966
    if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
9✔
967
      this.context.trace("Deleting {} skipped as the path does not exist.", path);
10✔
968
      return;
1✔
969
    }
970
    this.context.debug("Deleting {} ...", path);
10✔
971
    try {
972
      if (Files.isSymbolicLink(path) || isJunction(path)) {
7!
973
        Files.delete(path);
3✔
974
      } else {
975
        deleteRecursive(path);
3✔
976
      }
977
    } catch (IOException e) {
×
978
      throw new IllegalStateException("Failed to delete " + path, e);
×
979
    }
1✔
980
  }
1✔
981

982
  private void deleteRecursive(Path path) throws IOException {
983

984
    if (Files.isDirectory(path)) {
5✔
985
      try (Stream<Path> childStream = Files.list(path)) {
3✔
986
        Iterator<Path> iterator = childStream.iterator();
3✔
987
        while (iterator.hasNext()) {
3✔
988
          Path child = iterator.next();
4✔
989
          deleteRecursive(child);
3✔
990
        }
1✔
991
      }
992
    }
993
    this.context.trace("Deleting {} ...", path);
10✔
994
    boolean isSetWritable = setWritable(path, true);
5✔
995
    if (!isSetWritable) {
2✔
996
      this.context.debug("Couldn't give write access to file: " + path);
6✔
997
    }
998
    Files.delete(path);
2✔
999
  }
1✔
1000

1001
  @Override
1002
  public Path findFirst(Path dir, Predicate<Path> filter, boolean recursive) {
1003

1004
    try {
1005
      if (!Files.isDirectory(dir)) {
5✔
1006
        return null;
2✔
1007
      }
1008
      return findFirstRecursive(dir, filter, recursive);
6✔
1009
    } catch (IOException e) {
×
1010
      throw new IllegalStateException("Failed to search for file in " + dir, e);
×
1011
    }
1012
  }
1013

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

1016
    List<Path> folders = null;
2✔
1017
    try (Stream<Path> childStream = Files.list(dir)) {
3✔
1018
      Iterator<Path> iterator = childStream.iterator();
3✔
1019
      while (iterator.hasNext()) {
3✔
1020
        Path child = iterator.next();
4✔
1021
        if (filter.test(child)) {
4✔
1022
          return child;
4✔
1023
        } else if (recursive && Files.isDirectory(child)) {
2!
1024
          if (folders == null) {
×
1025
            folders = new ArrayList<>();
×
1026
          }
1027
          folders.add(child);
×
1028
        }
1029
      }
1✔
1030
    }
4!
1031
    if (folders != null) {
2!
1032
      for (Path child : folders) {
×
1033
        Path match = findFirstRecursive(child, filter, recursive);
×
1034
        if (match != null) {
×
1035
          return match;
×
1036
        }
1037
      }
×
1038
    }
1039
    return null;
2✔
1040
  }
1041

1042
  @Override
1043
  public List<Path> listChildrenMapped(Path dir, Function<Path, Path> filter) {
1044

1045
    if (!Files.isDirectory(dir)) {
5✔
1046
      return List.of();
2✔
1047
    }
1048
    List<Path> children = new ArrayList<>();
4✔
1049
    try (Stream<Path> childStream = Files.list(dir)) {
3✔
1050
      Iterator<Path> iterator = childStream.iterator();
3✔
1051
      while (iterator.hasNext()) {
3✔
1052
        Path child = iterator.next();
4✔
1053
        Path filteredChild = filter.apply(child);
5✔
1054
        if (filteredChild != null) {
2✔
1055
          if (filteredChild == child) {
3!
1056
            this.context.trace("Accepted file {}", child);
11✔
1057
          } else {
1058
            this.context.trace("Accepted file {} and mapped to {}", child, filteredChild);
×
1059
          }
1060
          children.add(filteredChild);
5✔
1061
        } else {
1062
          this.context.trace("Ignoring file {} according to filter", child);
10✔
1063
        }
1064
      }
1✔
1065
    } catch (IOException e) {
×
1066
      throw new IllegalStateException("Failed to find children of directory " + dir, e);
×
1067
    }
1✔
1068
    return children;
2✔
1069
  }
1070

1071
  @Override
1072
  public boolean isEmptyDir(Path dir) {
1073

1074
    return listChildren(dir, f -> true).isEmpty();
8✔
1075
  }
1076

1077
  private long getFileSize(Path file) {
1078

1079
    try {
1080
      return Files.size(file);
3✔
1081
    } catch (IOException e) {
×
1082
      this.context.warning(e.getMessage(), e);
×
1083
      return 0;
×
1084
    }
1085
  }
1086

1087
  private long getFileSizeRecursive(Path path) {
1088

1089
    long size = 0;
2✔
1090
    if (Files.isDirectory(path)) {
5✔
1091
      try (Stream<Path> childStream = Files.list(path)) {
3✔
1092
        Iterator<Path> iterator = childStream.iterator();
3✔
1093
        while (iterator.hasNext()) {
3✔
1094
          Path child = iterator.next();
4✔
1095
          size += getFileSizeRecursive(child);
6✔
1096
        }
1✔
1097
      } catch (IOException e) {
×
1098
        throw new RuntimeException("Failed to iterate children of folder " + path, e);
×
1099
      }
1✔
1100
    } else {
1101
      size += getFileSize(path);
6✔
1102
    }
1103
    return size;
2✔
1104
  }
1105

1106
  @Override
1107
  public Path findExistingFile(String fileName, List<Path> searchDirs) {
1108

1109
    for (Path dir : searchDirs) {
10!
1110
      Path filePath = dir.resolve(fileName);
4✔
1111
      try {
1112
        if (Files.exists(filePath)) {
5✔
1113
          return filePath;
2✔
1114
        }
1115
      } catch (Exception e) {
×
1116
        throw new IllegalStateException("Unexpected error while checking existence of file " + filePath + " .", e);
×
1117
      }
1✔
1118
    }
1✔
1119
    return null;
×
1120
  }
1121

1122
  @Override
1123
  public boolean setWritable(Path file, boolean writable) {
1124
    try {
1125
      // POSIX
1126
      PosixFileAttributeView posix = Files.getFileAttributeView(file, PosixFileAttributeView.class);
7✔
1127
      if (posix != null) {
2!
1128
        Set<PosixFilePermission> permissions = new HashSet<>(posix.readAttributes().permissions());
7✔
1129
        boolean changed;
1130
        if (writable) {
2!
1131
          changed = permissions.add(PosixFilePermission.OWNER_WRITE);
5✔
1132
        } else {
1133
          changed = permissions.remove(PosixFilePermission.OWNER_WRITE);
×
1134
        }
1135
        if (changed) {
2!
1136
          posix.setPermissions(permissions);
×
1137
        }
1138
        return true;
2✔
1139
      }
1140

1141
      // Windows
1142
      DosFileAttributeView dos = Files.getFileAttributeView(file, DosFileAttributeView.class);
×
1143
      if (dos != null) {
×
1144
        dos.setReadOnly(!writable);
×
1145
        return true;
×
1146
      }
1147

1148
      this.context.debug("Failed to set writing permission for file {}", file);
×
1149
      return false;
×
1150

1151
    } catch (IOException e) {
1✔
1152
      this.context.debug("Error occurred when trying to set writing permission for file " + file + ": " + e);
8✔
1153
      return false;
2✔
1154
    }
1155
  }
1156

1157
  @Override
1158
  public void makeExecutable(Path path, boolean confirm) {
1159

1160
    if (Files.exists(path)) {
5✔
1161
      if (skipPermissionsIfWindows(path)) {
4!
1162
        return;
×
1163
      }
1164
      Set<PosixFilePermission> existingPosixPermissions;
1165
      try {
1166
        // Read the current file permissions
1167
        existingPosixPermissions = Files.getPosixFilePermissions(path);
5✔
1168
      } catch (IOException e) {
×
1169
        throw new RuntimeException("Failed to get permissions for " + path, e);
×
1170
      }
1✔
1171

1172
      PathPermissions existingPermissions = PathPermissions.of(existingPosixPermissions);
3✔
1173
      PathPermissions executablePermissions = existingPermissions.makeExecutable();
3✔
1174
      boolean update = (executablePermissions != existingPermissions);
7✔
1175
      if (update) {
2✔
1176
        if (confirm) {
2!
1177
          boolean yesContinue = this.context.question(
×
1178
              "We want to execute {} but this command seems to lack executable permissions!\n"
1179
                  + "Most probably the tool vendor did forgot to add x-flags in the binary release package.\n"
1180
                  + "Before running the command, we suggest to set executable permissions to the file:\n"
1181
                  + "{}\n"
1182
                  + "For security reasons we ask for your confirmation so please check this request.\n"
1183
                  + "Changing permissions from {} to {}.\n"
1184
                  + "Do you confirm to make the command executable before running it?", path.getFileName(), path, existingPermissions, executablePermissions);
×
1185
          if (!yesContinue) {
×
1186
            return;
×
1187
          }
1188
        }
1189
        setFilePermissions(path, executablePermissions, false);
6✔
1190
      } else {
1191
        this.context.trace("Executable flags already present so no need to set them for file {}", path);
10✔
1192
      }
1193
    } else {
1✔
1194
      this.context.warning("Cannot set executable flag on file that does not exist: {}", path);
10✔
1195
    }
1196
  }
1✔
1197

1198
  @Override
1199
  public void setFilePermissions(Path path, PathPermissions permissions, boolean logErrorAndContinue) {
1200

1201
    if (skipPermissionsIfWindows(path)) {
4!
1202
      return;
×
1203
    }
1204
    try {
1205
      this.context.debug("Setting permissions for {} to {}", path, permissions);
14✔
1206
      // Set the new permissions
1207
      Files.setPosixFilePermissions(path, permissions.toPosix());
5✔
1208
    } catch (IOException e) {
×
1209
      if (logErrorAndContinue) {
×
1210
        this.context.warning().log(e, "Failed to set permissions to {} for path {}", permissions, path);
×
1211
      } else {
1212
        throw new RuntimeException("Failed to set permissions to " + permissions + " for path " + path, e);
×
1213
      }
1214
    }
1✔
1215
  }
1✔
1216

1217
  private boolean skipPermissionsIfWindows(Path path) {
1218
    if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
1219
      this.context.trace("Windows does not have file permissions hence omitting for {}", path);
×
1220
      return true;
×
1221
    }
1222
    return false;
2✔
1223
  }
1224

1225
  @Override
1226
  public void touch(Path file) {
1227

1228
    if (Files.exists(file)) {
5✔
1229
      try {
1230
        Files.setLastModifiedTime(file, FileTime.fromMillis(System.currentTimeMillis()));
5✔
1231
      } catch (IOException e) {
×
1232
        throw new IllegalStateException("Could not update modification-time of " + file, e);
×
1233
      }
1✔
1234
    } else {
1235
      try {
1236
        Files.createFile(file);
5✔
1237
      } catch (IOException e) {
1✔
1238
        throw new IllegalStateException("Could not create empty file " + file, e);
8✔
1239
      }
1✔
1240
    }
1241
  }
1✔
1242

1243
  @Override
1244
  public String readFileContent(Path file) {
1245

1246
    this.context.trace("Reading content of file from {}", file);
10✔
1247
    if (!Files.exists((file))) {
5!
1248
      this.context.debug("File {} does not exist", file);
×
1249
      return null;
×
1250
    }
1251
    try {
1252
      String content = Files.readString(file);
3✔
1253
      this.context.trace("Completed reading {} character(s) from file {}", content.length(), file);
16✔
1254
      return content;
2✔
1255
    } catch (IOException e) {
×
1256
      throw new IllegalStateException("Failed to read file " + file, e);
×
1257
    }
1258
  }
1259

1260
  @Override
1261
  public void writeFileContent(String content, Path file, boolean createParentDir) {
1262

1263
    if (createParentDir) {
2✔
1264
      mkdirs(file.getParent());
4✔
1265
    }
1266
    if (content == null) {
2!
1267
      content = "";
×
1268
    }
1269
    this.context.trace("Writing content with {} character(s) to file {}", content.length(), file);
16✔
1270
    if (Files.exists(file)) {
5✔
1271
      this.context.info("Overriding content of file {}", file);
10✔
1272
    }
1273
    try {
1274
      Files.writeString(file, content);
6✔
1275
      this.context.trace("Wrote content to file {}", file);
10✔
1276
    } catch (IOException e) {
×
1277
      throw new RuntimeException("Failed to write file " + file, e);
×
1278
    }
1✔
1279
  }
1✔
1280

1281
  @Override
1282
  public List<String> readFileLines(Path file) {
1283

1284
    this.context.trace("Reading content of file from {}", file);
10✔
1285
    if (!Files.exists(file)) {
5✔
1286
      this.context.warning("File {} does not exist", file);
10✔
1287
      return null;
2✔
1288
    }
1289
    try {
1290
      List<String> content = Files.readAllLines(file);
3✔
1291
      this.context.trace("Completed reading {} lines from file {}", content.size(), file);
16✔
1292
      return content;
2✔
1293
    } catch (IOException e) {
×
1294
      throw new IllegalStateException("Failed to read file " + file, e);
×
1295
    }
1296
  }
1297

1298
  @Override
1299
  public void writeFileLines(List<String> content, Path file, boolean createParentDir) {
1300

1301
    if (createParentDir) {
2!
1302
      mkdirs(file.getParent());
×
1303
    }
1304
    if (content == null) {
2!
1305
      content = List.of();
×
1306
    }
1307
    this.context.trace("Writing content with {} lines to file {}", content.size(), file);
16✔
1308
    if (Files.exists(file)) {
5✔
1309
      this.context.debug("Overriding content of file {}", file);
10✔
1310
    }
1311
    try {
1312
      Files.write(file, content);
6✔
1313
      this.context.trace("Wrote content to file {}", file);
10✔
1314
    } catch (IOException e) {
×
1315
      throw new RuntimeException("Failed to write file " + file, e);
×
1316
    }
1✔
1317
  }
1✔
1318

1319
  @Override
1320
  public void readProperties(Path file, Properties properties) {
1321

1322
    try (Reader reader = Files.newBufferedReader(file)) {
3✔
1323
      properties.load(reader);
3✔
1324
      this.context.debug("Successfully loaded {} properties from {}", properties.size(), file);
16✔
1325
    } catch (IOException e) {
×
1326
      throw new IllegalStateException("Failed to read properties file: " + file, e);
×
1327
    }
1✔
1328
  }
1✔
1329

1330
  @Override
1331
  public void writeProperties(Properties properties, Path file, boolean createParentDir) {
1332

1333
    if (createParentDir) {
2✔
1334
      mkdirs(file.getParent());
4✔
1335
    }
1336
    try (Writer writer = Files.newBufferedWriter(file)) {
5✔
1337
      properties.store(writer, null); // do not get confused - Java still writes a date/time header that cannot be omitted
4✔
1338
      this.context.debug("Successfully saved {} properties to {}", properties.size(), file);
16✔
1339
    } catch (IOException e) {
×
1340
      throw new IllegalStateException("Failed to save properties file during tests.", e);
×
1341
    }
1✔
1342
  }
1✔
1343

1344
  @Override
1345
  public void readIniFile(Path file, IniFile iniFile) {
1346
    if (!Files.exists(file)) {
5!
1347
      this.context.debug("INI file {} does not exist.", iniFile);
×
1348
      return;
×
1349
    }
1350
    List<String> iniLines = readFileLines(file);
4✔
1351
    IniSection currentIniSection = iniFile.getInitialSection();
3✔
1352
    for (String line : iniLines) {
10✔
1353
      if (line.trim().startsWith("[")) {
5✔
1354
        currentIniSection = iniFile.getOrCreateSection(line);
5✔
1355
      } else if (line.isBlank() || IniComment.COMMENT_SYMBOLS.contains(line.trim().charAt(0))) {
11✔
1356
        currentIniSection.addComment(line);
4✔
1357
      } else {
1358
        int index = line.indexOf('=');
4✔
1359
        if (index > 0) {
2!
1360
          currentIniSection.setProperty(line);
3✔
1361
        }
1362
      }
1363
    }
1✔
1364
  }
1✔
1365

1366
  @Override
1367
  public void writeIniFile(IniFile iniFile, Path file, boolean createParentDir) {
1368
    String iniString = iniFile.toString();
3✔
1369
    writeFileContent(iniString, file, createParentDir);
5✔
1370
  }
1✔
1371

1372
  @Override
1373
  public Duration getFileAge(Path path) {
1374
    if (Files.exists(path)) {
5✔
1375
      try {
1376
        long currentTime = System.currentTimeMillis();
2✔
1377
        long fileModifiedTime = Files.getLastModifiedTime(path).toMillis();
6✔
1378
        return Duration.ofMillis(currentTime - fileModifiedTime);
5✔
1379
      } catch (IOException e) {
×
1380
        this.context.warning().log(e, "Could not get modification-time of {}.", path);
×
1381
      }
×
1382
    } else {
1383
      this.context.debug("Path {} is missing - skipping modification-time and file age check.", path);
10✔
1384
    }
1385
    return null;
2✔
1386
  }
1387

1388
  @Override
1389
  public boolean isFileAgeRecent(Path path, Duration cacheDuration) {
1390

1391
    Duration age = getFileAge(path);
4✔
1392
    if (age == null) {
2✔
1393
      return false;
2✔
1394
    }
1395
    context.debug("The path {} was last updated {} ago and caching duration is {}.", path, age, cacheDuration);
18✔
1396
    return (age.toMillis() <= cacheDuration.toMillis());
10✔
1397
  }
1398
}
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