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

devonfw / IDEasy / 17686304215

12 Sep 2025 09:19PM UTC coverage: 68.673% (+0.05%) from 68.62%
17686304215

push

github

web-flow
#1476: fix extract to support links (#1479)

3397 of 5415 branches covered (62.73%)

Branch coverage included in aggregate %.

8868 of 12445 relevant lines covered (71.26%)

3.13 hits per line

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

66.88
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 target = resolveRelativePathSecure(tae.getLinkName(), root);
×
761
            links.add(new PathLink(entryPath, target, linkType));
×
762
            mkdirs(entryPath.getParent());
×
763
          }
764
        }
765
        if (entry.isDirectory()) {
3✔
766
          mkdirs(entryPath);
4✔
767
        } else if (linkType == null) { // regular file
2!
768
          mkdirs(entryPath.getParent());
4✔
769
          Files.copy(ais, entryPath, StandardCopyOption.REPLACE_EXISTING);
10✔
770
          // POSIX perms on non-Windows
771
          if (!isWindows && (permissions != null)) {
4!
772
            setFilePermissions(entryPath, permissions, false);
5✔
773
          }
774
        }
775
        pb.stepBy(Math.max(0L, entry.getSize()));
6✔
776
        entry = ais.getNextEntry();
3✔
777
      }
1✔
778
      // post process links
779
      for (PathLink link : links) {
6!
780
        link(link);
×
781
      }
×
782
    } catch (Exception e) {
×
783
      throw new IllegalStateException("Failed to extract " + file + " to " + targetDir, e);
×
784
    }
1✔
785
  }
1✔
786

787
  private Path resolveRelativePathSecure(String entryName, Path root) {
788

789
    Path entryPath = root.resolve(entryName).normalize();
5✔
790
    if (!entryPath.startsWith(root)) {
4!
791
      throw new IllegalStateException("Preventing path traversal attack from " + entryName + " to " + entryPath);
×
792
    }
793
    return entryPath;
2✔
794
  }
795

796

797
  @Override
798
  public void extractDmg(Path file, Path targetDir) {
799

800
    this.context.info("Extracting DMG file {} to {}", file, targetDir);
×
801
    assert this.context.getSystemInfo().isMac();
×
802

803
    Path mountPath = this.context.getIdeHome().resolve(IdeContext.FOLDER_UPDATES).resolve(IdeContext.FOLDER_VOLUME);
×
804
    mkdirs(mountPath);
×
805
    ProcessContext pc = this.context.newProcess();
×
806
    pc.executable("hdiutil");
×
807
    pc.addArgs("attach", "-quiet", "-nobrowse", "-mountpoint", mountPath, file);
×
808
    pc.run();
×
809
    Path appPath = findFirst(mountPath, p -> p.getFileName().toString().endsWith(".app"), false);
×
810
    if (appPath == null) {
×
811
      throw new IllegalStateException("Failed to unpack DMG as no MacOS *.app was found in file " + file);
×
812
    }
813

814
    copy(appPath, targetDir, FileCopyMode.COPY_TREE_OVERRIDE_TREE);
×
815
    pc.addArgs("detach", "-force", mountPath);
×
816
    pc.run();
×
817
  }
×
818

819
  @Override
820
  public void extractMsi(Path file, Path targetDir) {
821

822
    this.context.info("Extracting MSI file {} to {}", file, targetDir);
×
823
    this.context.newProcess().executable("msiexec").addArgs("/a", file, "/qn", "TARGETDIR=" + targetDir).run();
×
824
    // msiexec also creates a copy of the MSI
825
    Path msiCopy = targetDir.resolve(file.getFileName());
×
826
    delete(msiCopy);
×
827
  }
×
828

829
  @Override
830
  public void extractPkg(Path file, Path targetDir) {
831

832
    this.context.info("Extracting PKG file {} to {}", file, targetDir);
×
833
    Path tmpDirPkg = createTempDir("ide-pkg-");
×
834
    ProcessContext pc = this.context.newProcess();
×
835
    // we might also be able to use cpio from commons-compression instead of external xar...
836
    pc.executable("xar").addArgs("-C", tmpDirPkg, "-xf", file).run();
×
837
    Path contentPath = findFirst(tmpDirPkg, p -> p.getFileName().toString().equals("Payload"), true);
×
838
    extractTar(contentPath, targetDir, TarCompression.GZ);
×
839
    delete(tmpDirPkg);
×
840
  }
×
841

842
  @Override
843
  public void compress(Path dir, OutputStream out, String format) {
844

845
    String extension = FilenameUtil.getExtension(format);
3✔
846
    TarCompression tarCompression = TarCompression.of(extension);
3✔
847
    if (tarCompression != null) {
2!
848
      compressTar(dir, out, tarCompression);
6✔
849
    } else if (extension.equals("zip")) {
×
850
      compressZip(dir, out);
×
851
    } else {
852
      throw new IllegalArgumentException("Unsupported extension: " + extension);
×
853
    }
854
  }
1✔
855

856
  @Override
857
  public void compressTar(Path dir, OutputStream out, TarCompression tarCompression) {
858
    switch (tarCompression) {
8!
859
      case null -> compressTar(dir, out);
×
860
      case NONE -> compressTar(dir, out);
×
861
      case GZ -> compressTarGz(dir, out);
5✔
862
      case BZIP2 -> compressTarBzip2(dir, out);
×
863
      default -> throw new IllegalArgumentException("Unsupported tar compression: " + tarCompression);
×
864
    }
865
  }
1✔
866

867
  @Override
868
  public void compressTarGz(Path dir, OutputStream out) {
869
    try (GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(out)) {
5✔
870
      compressTarOrThrow(dir, gzOut);
4✔
871
    } catch (IOException e) {
×
872
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar.gz file.", e);
×
873
    }
1✔
874
  }
1✔
875

876
  @Override
877
  public void compressTarBzip2(Path dir, OutputStream out) {
878
    try (BZip2CompressorOutputStream bzip2Out = new BZip2CompressorOutputStream(out)) {
×
879
      compressTarOrThrow(dir, bzip2Out);
×
880
    } catch (IOException e) {
×
881
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar.bz2 file.", e);
×
882
    }
×
883
  }
×
884

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

894
  private void compressTarOrThrow(Path dir, OutputStream out) throws IOException {
895
    try (TarArchiveOutputStream tarOut = new TarArchiveOutputStream(out)) {
5✔
896
      compressRecursive(dir, tarOut, "");
5✔
897
      tarOut.finish();
2✔
898
    }
899
  }
1✔
900

901
  @Override
902
  public void compressZip(Path dir, OutputStream out) {
903
    try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(out)) {
×
904
      compressRecursive(dir, zipOut, "");
×
905
      zipOut.finish();
×
906
    } catch (IOException e) {
×
907
      throw new IllegalStateException("Failed to compress directory " + dir + " to zip file.", e);
×
908
    }
×
909
  }
×
910

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

955
  @Override
956
  public void delete(Path path) {
957

958
    if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
9✔
959
      this.context.trace("Deleting {} skipped as the path does not exist.", path);
10✔
960
      return;
1✔
961
    }
962
    this.context.debug("Deleting {} ...", path);
10✔
963
    try {
964
      if (Files.isSymbolicLink(path) || isJunction(path)) {
7!
965
        Files.delete(path);
3✔
966
      } else {
967
        deleteRecursive(path);
3✔
968
      }
969
    } catch (IOException e) {
×
970
      throw new IllegalStateException("Failed to delete " + path, e);
×
971
    }
1✔
972
  }
1✔
973

974
  private void deleteRecursive(Path path) throws IOException {
975

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

993
  @Override
994
  public Path findFirst(Path dir, Predicate<Path> filter, boolean recursive) {
995

996
    try {
997
      if (!Files.isDirectory(dir)) {
5✔
998
        return null;
2✔
999
      }
1000
      return findFirstRecursive(dir, filter, recursive);
6✔
1001
    } catch (IOException e) {
×
1002
      throw new IllegalStateException("Failed to search for file in " + dir, e);
×
1003
    }
1004
  }
1005

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

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

1034
  @Override
1035
  public List<Path> listChildrenMapped(Path dir, Function<Path, Path> filter) {
1036

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

1063
  @Override
1064
  public boolean isEmptyDir(Path dir) {
1065

1066
    return listChildren(dir, f -> true).isEmpty();
8✔
1067
  }
1068

1069
  private long getFileSize(Path file) {
1070

1071
    try {
1072
      return Files.size(file);
3✔
1073
    } catch (IOException e) {
×
1074
      this.context.warning(e.getMessage(), e);
×
1075
      return 0;
×
1076
    }
1077
  }
1078

1079
  private long getFileSizeRecursive(Path path) {
1080

1081
    long size = 0;
2✔
1082
    if (Files.isDirectory(path)) {
5✔
1083
      try (Stream<Path> childStream = Files.list(path)) {
3✔
1084
        Iterator<Path> iterator = childStream.iterator();
3✔
1085
        while (iterator.hasNext()) {
3✔
1086
          Path child = iterator.next();
4✔
1087
          size += getFileSizeRecursive(child);
6✔
1088
        }
1✔
1089
      } catch (IOException e) {
×
1090
        throw new RuntimeException("Failed to iterate children of folder " + path, e);
×
1091
      }
1✔
1092
    } else {
1093
      size += getFileSize(path);
6✔
1094
    }
1095
    return size;
2✔
1096
  }
1097

1098
  @Override
1099
  public Path findExistingFile(String fileName, List<Path> searchDirs) {
1100

1101
    for (Path dir : searchDirs) {
10!
1102
      Path filePath = dir.resolve(fileName);
4✔
1103
      try {
1104
        if (Files.exists(filePath)) {
5✔
1105
          return filePath;
2✔
1106
        }
1107
      } catch (Exception e) {
×
1108
        throw new IllegalStateException("Unexpected error while checking existence of file " + filePath + " .", e);
×
1109
      }
1✔
1110
    }
1✔
1111
    return null;
×
1112
  }
1113

1114
  @Override
1115
  public boolean setWritable(Path file, boolean writable) {
1116
    try {
1117
      // POSIX
1118
      PosixFileAttributeView posix = Files.getFileAttributeView(file, PosixFileAttributeView.class);
7✔
1119
      if (posix != null) {
2!
1120
        Set<PosixFilePermission> permissions = new HashSet<>(posix.readAttributes().permissions());
7✔
1121
        boolean changed;
1122
        if (writable) {
2!
1123
          changed = permissions.add(PosixFilePermission.OWNER_WRITE);
5✔
1124
        } else {
1125
          changed = permissions.remove(PosixFilePermission.OWNER_WRITE);
×
1126
        }
1127
        if (changed) {
2!
1128
          posix.setPermissions(permissions);
×
1129
        }
1130
        return true;
2✔
1131
      }
1132

1133
      // Windows
1134
      DosFileAttributeView dos = Files.getFileAttributeView(file, DosFileAttributeView.class);
×
1135
      if (dos != null) {
×
1136
        dos.setReadOnly(!writable);
×
1137
        return true;
×
1138
      }
1139

1140
      this.context.debug("Failed to set writing permission for file {}", file);
×
1141
      return false;
×
1142

1143
    } catch (IOException e) {
1✔
1144
      this.context.debug("Error occurred when trying to set writing permission for file " + file + ": " + e);
8✔
1145
      return false;
2✔
1146
    }
1147
  }
1148

1149
  @Override
1150
  public void makeExecutable(Path path, boolean confirm) {
1151

1152
    if (Files.exists(path)) {
5✔
1153
      if (skipPermissionsIfWindows(path)) {
4!
1154
        return;
×
1155
      }
1156
      Set<PosixFilePermission> existingPosixPermissions;
1157
      try {
1158
        // Read the current file permissions
1159
        existingPosixPermissions = Files.getPosixFilePermissions(path);
5✔
1160
      } catch (IOException e) {
×
1161
        throw new RuntimeException("Failed to get permissions for " + path, e);
×
1162
      }
1✔
1163

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

1190
  @Override
1191
  public void setFilePermissions(Path path, PathPermissions permissions, boolean logErrorAndContinue) {
1192

1193
    if (skipPermissionsIfWindows(path)) {
4!
1194
      return;
×
1195
    }
1196
    try {
1197
      this.context.debug("Setting permissions for {} to {}", path, permissions);
14✔
1198
      // Set the new permissions
1199
      Files.setPosixFilePermissions(path, permissions.toPosix());
5✔
1200
    } catch (IOException e) {
×
1201
      if (logErrorAndContinue) {
×
1202
        this.context.warning().log(e, "Failed to set permissions to {} for path {}", permissions, path);
×
1203
      } else {
1204
        throw new RuntimeException("Failed to set permissions to " + permissions + " for path " + path, e);
×
1205
      }
1206
    }
1✔
1207
  }
1✔
1208

1209
  private boolean skipPermissionsIfWindows(Path path) {
1210
    if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
1211
      this.context.trace("Windows does not have file permissions hence omitting for {}", path);
×
1212
      return true;
×
1213
    }
1214
    return false;
2✔
1215
  }
1216

1217
  @Override
1218
  public void touch(Path file) {
1219

1220
    if (Files.exists(file)) {
5✔
1221
      try {
1222
        Files.setLastModifiedTime(file, FileTime.fromMillis(System.currentTimeMillis()));
5✔
1223
      } catch (IOException e) {
×
1224
        throw new IllegalStateException("Could not update modification-time of " + file, e);
×
1225
      }
1✔
1226
    } else {
1227
      try {
1228
        Files.createFile(file);
5✔
1229
      } catch (IOException e) {
1✔
1230
        throw new IllegalStateException("Could not create empty file " + file, e);
8✔
1231
      }
1✔
1232
    }
1233
  }
1✔
1234

1235
  @Override
1236
  public String readFileContent(Path file) {
1237

1238
    this.context.trace("Reading content of file from {}", file);
10✔
1239
    if (!Files.exists((file))) {
5!
1240
      this.context.debug("File {} does not exist", file);
×
1241
      return null;
×
1242
    }
1243
    try {
1244
      String content = Files.readString(file);
3✔
1245
      this.context.trace("Completed reading {} character(s) from file {}", content.length(), file);
16✔
1246
      return content;
2✔
1247
    } catch (IOException e) {
×
1248
      throw new IllegalStateException("Failed to read file " + file, e);
×
1249
    }
1250
  }
1251

1252
  @Override
1253
  public void writeFileContent(String content, Path file, boolean createParentDir) {
1254

1255
    if (createParentDir) {
2✔
1256
      mkdirs(file.getParent());
4✔
1257
    }
1258
    if (content == null) {
2!
1259
      content = "";
×
1260
    }
1261
    this.context.trace("Writing content with {} character(s) to file {}", content.length(), file);
16✔
1262
    if (Files.exists(file)) {
5✔
1263
      this.context.info("Overriding content of file {}", file);
10✔
1264
    }
1265
    try {
1266
      Files.writeString(file, content);
6✔
1267
      this.context.trace("Wrote content to file {}", file);
10✔
1268
    } catch (IOException e) {
×
1269
      throw new RuntimeException("Failed to write file " + file, e);
×
1270
    }
1✔
1271
  }
1✔
1272

1273
  @Override
1274
  public List<String> readFileLines(Path file) {
1275

1276
    this.context.trace("Reading content of file from {}", file);
10✔
1277
    if (!Files.exists(file)) {
5✔
1278
      this.context.warning("File {} does not exist", file);
10✔
1279
      return null;
2✔
1280
    }
1281
    try {
1282
      List<String> content = Files.readAllLines(file);
3✔
1283
      this.context.trace("Completed reading {} lines from file {}", content.size(), file);
16✔
1284
      return content;
2✔
1285
    } catch (IOException e) {
×
1286
      throw new IllegalStateException("Failed to read file " + file, e);
×
1287
    }
1288
  }
1289

1290
  @Override
1291
  public void writeFileLines(List<String> content, Path file, boolean createParentDir) {
1292

1293
    if (createParentDir) {
2!
1294
      mkdirs(file.getParent());
×
1295
    }
1296
    if (content == null) {
2!
1297
      content = List.of();
×
1298
    }
1299
    this.context.trace("Writing content with {} lines to file {}", content.size(), file);
16✔
1300
    if (Files.exists(file)) {
5✔
1301
      this.context.debug("Overriding content of file {}", file);
10✔
1302
    }
1303
    try {
1304
      Files.write(file, content);
6✔
1305
      this.context.trace("Wrote content to file {}", file);
10✔
1306
    } catch (IOException e) {
×
1307
      throw new RuntimeException("Failed to write file " + file, e);
×
1308
    }
1✔
1309
  }
1✔
1310

1311
  @Override
1312
  public void readProperties(Path file, Properties properties) {
1313

1314
    try (Reader reader = Files.newBufferedReader(file)) {
3✔
1315
      properties.load(reader);
3✔
1316
      this.context.debug("Successfully loaded {} properties from {}", properties.size(), file);
16✔
1317
    } catch (IOException e) {
×
1318
      throw new IllegalStateException("Failed to read properties file: " + file, e);
×
1319
    }
1✔
1320
  }
1✔
1321

1322
  @Override
1323
  public void writeProperties(Properties properties, Path file, boolean createParentDir) {
1324

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

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

1358
  @Override
1359
  public void writeIniFile(IniFile iniFile, Path file, boolean createParentDir) {
1360
    String iniString = iniFile.toString();
3✔
1361
    writeFileContent(iniString, file, createParentDir);
5✔
1362
  }
1✔
1363

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

1380
  @Override
1381
  public boolean isFileAgeRecent(Path path, Duration cacheDuration) {
1382

1383
    Duration age = getFileAge(path);
4✔
1384
    if (age == null) {
2✔
1385
      return false;
2✔
1386
    }
1387
    context.debug("The path {} was last updated {} ago and caching duration is {}.", path, age, cacheDuration);
18✔
1388
    return (age.toMillis() <= cacheDuration.toMillis());
10✔
1389
  }
1390
}
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