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

devonfw / IDEasy / 21183545486

20 Jan 2026 06:52PM UTC coverage: 70.456% (+0.01%) from 70.445%
21183545486

push

github

web-flow
#1666: fixed integration-tests (#1686)

4033 of 6310 branches covered (63.91%)

Branch coverage included in aggregate %.

10483 of 14293 relevant lines covered (73.34%)

3.18 hits per line

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

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

43
import org.apache.commons.compress.archivers.ArchiveEntry;
44
import org.apache.commons.compress.archivers.ArchiveInputStream;
45
import org.apache.commons.compress.archivers.ArchiveOutputStream;
46
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
47
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
48
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
49
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
50
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;
51
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
52
import org.apache.commons.io.IOUtils;
53

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

68
/**
69
 * Implementation of {@link FileAccess}.
70
 */
71
public class FileAccessImpl extends HttpDownloader implements FileAccess {
72

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

75
  private static final String WINDOWS_FILE_LOCK_WARNING =
76
      "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"
77
          + WINDOWS_FILE_LOCK_DOCUMENTATION_PAGE;
78

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

81
  private final IdeContext context;
82

83
  /**
84
   * The constructor.
85
   *
86
   * @param context the {@link IdeContext} to use.
87
   */
88
  public FileAccessImpl(IdeContext context) {
89

90
    super();
2✔
91
    this.context = context;
3✔
92
  }
1✔
93

94
  @Override
95
  public void download(String url, Path target) {
96

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

112
  private void downloadViaHttp(String url, Path target) {
113

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

136
  private void downloadWithHttpVersion(String url, Path target, Version httpVersion) throws Exception {
137

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

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

160
    long contentLength = response.headers().firstValueAsLong("content-length").orElse(-1);
7✔
161
    if (contentLength < 0) {
4✔
162
      this.context.warning("Content-Length was not provided by download from {}", url);
10✔
163
    }
164

165
    byte[] data = new byte[1024];
3✔
166
    boolean fileComplete = false;
2✔
167
    int count;
168

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

187
  private void copyFileWithProgressBar(Path source, Path target) {
188

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

210
  @Override
211
  public String download(String url) {
212

213
    this.context.debug("Downloading text body from {}", url);
10✔
214
    return httpGetAsString(url);
3✔
215
  }
216

217
  @Override
218
  public void mkdirs(Path directory) {
219

220
    if (Files.isDirectory(directory)) {
5✔
221
      return;
1✔
222
    }
223
    this.context.trace("Creating directory {}", directory);
10✔
224
    try {
225
      Files.createDirectories(directory);
5✔
226
    } catch (IOException e) {
×
227
      throw new IllegalStateException("Failed to create directory " + directory, e);
×
228
    }
1✔
229
  }
1✔
230

231
  @Override
232
  public boolean isFile(Path file) {
233

234
    if (!Files.exists(file)) {
5!
235
      this.context.trace("File {} does not exist", file);
×
236
      return false;
×
237
    }
238
    if (Files.isDirectory(file)) {
5!
239
      this.context.trace("Path {} is a directory but a regular file was expected", file);
×
240
      return false;
×
241
    }
242
    return true;
2✔
243
  }
244

245
  @Override
246
  public boolean isExpectedFolder(Path folder) {
247

248
    if (Files.isDirectory(folder)) {
5✔
249
      return true;
2✔
250
    }
251
    this.context.warning("Expected folder was not found at {}", folder);
10✔
252
    return false;
2✔
253
  }
254

255
  @Override
256
  public String checksum(Path file, String hashAlgorithm) {
257

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

277
  @Override
278
  public boolean isJunction(Path path) {
279

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

301
  @Override
302
  public Path backup(Path fileOrFolder) {
303

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

329
  private static Path appendParentPath(Path path, Path parent, int max) {
330

331
    if ((parent == null) || (max <= 0)) {
4!
332
      return path;
2✔
333
    }
334
    return appendParentPath(path, parent.getParent(), max - 1).resolve(parent.getFileName());
11✔
335
  }
336

337
  @Override
338
  public void move(Path source, Path targetDir, StandardCopyOption... copyOptions) {
339

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

353
  @Override
354
  public void copy(Path source, Path target, FileCopyMode mode, PathCopyListener listener) {
355

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

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

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

422
  /**
423
   * 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
424
   * {@link Path} that is neither a symbolic link nor a Windows junction.
425
   *
426
   * @param path the {@link Path} to delete.
427
   */
428
  private void deleteLinkIfExists(Path path) {
429

430
    boolean isJunction = isJunction(path); // since broken junctions are not detected by Files.exists()
4✔
431
    boolean isSymlink = Files.exists(path, LinkOption.NOFOLLOW_LINKS) && Files.isSymbolicLink(path);
16!
432

433
    assert !(isSymlink && isJunction);
5!
434

435
    if (isJunction || isSymlink) {
4!
436
      this.context.info("Deleting previous " + (isJunction ? "junction" : "symlink") + " at " + path);
9!
437
      try {
438
        Files.delete(path);
2✔
439
      } catch (IOException e) {
×
440
        throw new IllegalStateException("Failed to delete link at " + path, e);
×
441
      }
1✔
442
    }
443
  }
1✔
444

445
  /**
446
   * Adapts the given {@link Path} to be relative or absolute depending on the given {@code relative} flag. Additionally, {@link Path#toRealPath(LinkOption...)}
447
   * is applied to {@code target}.
448
   *
449
   * @param target the {@link Path} the link should point to and that is to be adapted.
450
   * @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}.
451
   * @param relative the {@code relative} flag.
452
   * @return the adapted {@link Path}.
453
   * @see #symlink(Path, Path, boolean)
454
   */
455
  private Path adaptPath(Path target, Path link, boolean relative) {
456

457
    if (!target.isAbsolute()) {
3✔
458
      target = link.resolveSibling(target);
4✔
459
    }
460
    try {
461
      target = target.toRealPath(LinkOption.NOFOLLOW_LINKS); // to transform ../d1/../d2 to ../d2
9✔
462
    } catch (IOException e) {
×
463
      throw new RuntimeException("Failed to get real path of " + target, e);
×
464
    }
1✔
465
    if (relative) {
2✔
466
      target = link.getParent().relativize(target);
5✔
467
      // to make relative links like this work: dir/link -> dir
468
      target = (target.toString().isEmpty()) ? Path.of(".") : target;
11✔
469
    }
470
    return target;
2✔
471
  }
472

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

482
    this.context.trace("Creating a Windows {} at {} pointing to {}", type, link, target);
×
483
    ProcessContext pc = this.context.newProcess().executable("cmd").addArgs("/c", "mklink", type.getMklinkOption());
×
484
    Path parent = link.getParent();
×
485
    if (parent == null) {
×
486
      parent = Path.of(".");
×
487
    }
488
    Path absolute = parent.resolve(target).toAbsolutePath().normalize();
×
489
    if (type == PathLinkType.SYMBOLIC_LINK && Files.isDirectory(absolute)) {
×
490
      pc = pc.addArg("/j");
×
491
      target = absolute;
×
492
    }
493
    pc = pc.addArgs(link.toString(), target.toString());
×
494
    ProcessResult result = pc.run(ProcessMode.DEFAULT);
×
495
    result.failOnError();
×
496
  }
×
497

498
  @Override
499
  public void link(Path source, Path link, boolean relative, PathLinkType type) {
500

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

533
  @Override
534
  public Path toRealPath(Path path) {
535

536
    return toRealPath(path, true);
5✔
537
  }
538

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

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

545
  private Path toRealPath(Path path, boolean resolveLinks) {
546

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

563
  @Override
564
  public Path createTempDir(String name) {
565

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

584
  @Override
585
  public void extract(Path archiveFile, Path targetDir, Consumer<Path> postExtractHook, boolean extract) {
586

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

625
  private void postExtractHook(Consumer<Path> postExtractHook, Path properInstallDir) {
626

627
    if (postExtractHook != null) {
2✔
628
      postExtractHook.accept(properInstallDir);
3✔
629
    }
630
  }
1✔
631

632
  /**
633
   * @param path the {@link Path} to start the recursive search from.
634
   * @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
635
   *     item in their respective directory and {@code s} is not named "bin".
636
   */
637
  private Path getProperInstallationSubDirOf(Path path, Path archiveFile) {
638

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

656
  @Override
657
  public void extractZip(Path file, Path targetDir) {
658

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

676
  @SuppressWarnings("unchecked")
677
  private void onFileCopiedFromZip(Path source, Path target, boolean directory, IdeProgressBar progressBar) {
678

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

695
  @Override
696
  public void extractTar(Path file, Path targetDir, TarCompression compression) {
697

698
    extractArchive(file, targetDir, in -> new TarArchiveInputStream(compression.unpack(in)));
13✔
699
  }
1✔
700

701
  @Override
702
  public void extractJar(Path file, Path targetDir) {
703

704
    extractZip(file, targetDir);
4✔
705
  }
1✔
706

707
  /**
708
   * @param permissions The integer as returned by {@link TarArchiveEntry#getMode()} that represents the file permissions of a file on a Unix file system.
709
   * @return A String representing the file permissions. E.g. "rwxrwxr-x" or "rw-rw-r--"
710
   */
711
  public static String generatePermissionString(int permissions) {
712

713
    // Ensure that only the last 9 bits are considered
714
    permissions &= 0b111111111;
4✔
715

716
    StringBuilder permissionStringBuilder = new StringBuilder("rwxrwxrwx");
5✔
717
    for (int i = 0; i < 9; i++) {
7✔
718
      int mask = 1 << i;
4✔
719
      char currentChar = ((permissions & mask) != 0) ? permissionStringBuilder.charAt(8 - i) : '-';
12✔
720
      permissionStringBuilder.setCharAt(8 - i, currentChar);
6✔
721
    }
722

723
    return permissionStringBuilder.toString();
3✔
724
  }
725

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

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

730
    final List<PathLink> links = new ArrayList<>();
4✔
731
    try (InputStream is = Files.newInputStream(file);
5✔
732
        ArchiveInputStream<?> ais = unpacker.apply(is);
5✔
733
        IdeProgressBar pb = this.context.newProgressbarForExtracting(getFileSize(file))) {
7✔
734

735
      final Path root = targetDir.toAbsolutePath().normalize();
4✔
736

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

782
  private Path resolveRelativePathSecure(String entryName, Path root) {
783

784
    Path entryPath = root.resolve(entryName).normalize();
5✔
785
    return resolveRelativePathSecure(entryPath, root, entryName);
6✔
786
  }
787

788
  private Path resolveRelativePathSecure(Path entryPath, Path root, String entryName) {
789

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

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

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

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

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

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

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

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

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

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

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

855
  @Override
856
  public void compressTar(Path dir, OutputStream out, TarCompression tarCompression) {
857

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

870
    try (GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(out)) {
5✔
871
      compressTarOrThrow(dir, gzOut);
4✔
872
    } catch (IOException e) {
×
873
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar.gz file.", e);
×
874
    }
1✔
875
  }
1✔
876

877
  @Override
878
  public void compressTarBzip2(Path dir, OutputStream out) {
879

880
    try (BZip2CompressorOutputStream bzip2Out = new BZip2CompressorOutputStream(out)) {
×
881
      compressTarOrThrow(dir, bzip2Out);
×
882
    } catch (IOException e) {
×
883
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar.bz2 file.", e);
×
884
    }
×
885
  }
×
886

887
  @Override
888
  public void compressTar(Path dir, OutputStream out) {
889

890
    try {
891
      compressTarOrThrow(dir, out);
×
892
    } catch (IOException e) {
×
893
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar file.", e);
×
894
    }
×
895
  }
×
896

897
  private void compressTarOrThrow(Path dir, OutputStream out) throws IOException {
898

899
    try (TarArchiveOutputStream tarOut = new TarArchiveOutputStream(out)) {
5✔
900
      compressRecursive(dir, tarOut, "");
5✔
901
      tarOut.finish();
2✔
902
    }
903
  }
1✔
904

905
  @Override
906
  public void compressZip(Path dir, OutputStream out) {
907

908
    try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(out)) {
×
909
      compressRecursive(dir, zipOut, "");
×
910
      zipOut.finish();
×
911
    } catch (IOException e) {
×
912
      throw new IllegalStateException("Failed to compress directory " + dir + " to zip file.", e);
×
913
    }
×
914
  }
×
915

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

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

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

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

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

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

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

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

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

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

1033
  @Override
1034
  public Path findAncestor(Path path, Path baseDir, int subfolderCount) {
1035

1036
    if ((path == null) || (baseDir == null)) {
4!
1037
      this.context.debug("Path should not be null for findAncestor.");
4✔
1038
      return null;
2✔
1039
    }
1040
    if (subfolderCount <= 0) {
2!
1041
      throw new IllegalArgumentException("Subfolder count: " + subfolderCount);
×
1042
    }
1043
    // 1. option relativize
1044
    // 2. recursive getParent
1045
    // 3. loop getParent???
1046
    // 4. getName + getNameCount
1047
    path = path.toAbsolutePath().normalize();
4✔
1048
    baseDir = baseDir.toAbsolutePath().normalize();
4✔
1049
    int directoryNameCount = path.getNameCount();
3✔
1050
    int baseDirNameCount = baseDir.getNameCount();
3✔
1051
    int delta = directoryNameCount - baseDirNameCount - subfolderCount;
6✔
1052
    if (delta < 0) {
2!
1053
      return null;
×
1054
    }
1055
    // ensure directory is a sub-folder of baseDir
1056
    for (int i = 0; i < baseDirNameCount; i++) {
7✔
1057
      if (!path.getName(i).toString().equals(baseDir.getName(i).toString())) {
10✔
1058
        return null;
2✔
1059
      }
1060
    }
1061
    Path result = path;
2✔
1062
    while (delta > 0) {
2✔
1063
      result = result.getParent();
3✔
1064
      delta--;
2✔
1065
    }
1066
    return result;
2✔
1067
  }
1068

1069
  @Override
1070
  public List<Path> listChildrenMapped(Path dir, Function<Path, Path> filter) {
1071

1072
    if (!Files.isDirectory(dir)) {
5✔
1073
      return List.of();
2✔
1074
    }
1075
    List<Path> children = new ArrayList<>();
4✔
1076
    try (Stream<Path> childStream = Files.list(dir)) {
3✔
1077
      Iterator<Path> iterator = childStream.iterator();
3✔
1078
      while (iterator.hasNext()) {
3✔
1079
        Path child = iterator.next();
4✔
1080
        Path filteredChild = filter.apply(child);
5✔
1081
        if (filteredChild != null) {
2✔
1082
          if (filteredChild == child) {
3!
1083
            this.context.trace("Accepted file {}", child);
11✔
1084
          } else {
1085
            this.context.trace("Accepted file {} and mapped to {}", child, filteredChild);
×
1086
          }
1087
          children.add(filteredChild);
5✔
1088
        } else {
1089
          this.context.trace("Ignoring file {} according to filter", child);
10✔
1090
        }
1091
      }
1✔
1092
    } catch (IOException e) {
×
1093
      throw new IllegalStateException("Failed to find children of directory " + dir, e);
×
1094
    }
1✔
1095
    return children;
2✔
1096
  }
1097

1098
  @Override
1099
  public boolean isEmptyDir(Path dir) {
1100

1101
    return listChildren(dir, f -> true).isEmpty();
8✔
1102
  }
1103

1104
  @Override
1105
  public boolean isNonEmptyFile(Path file) {
1106

1107
    if (Files.isRegularFile(file)) {
5✔
1108
      return (getFileSize(file) > 0);
10✔
1109
    }
1110
    return false;
2✔
1111
  }
1112

1113
  private long getFileSize(Path file) {
1114

1115
    try {
1116
      return Files.size(file);
3✔
1117
    } catch (IOException e) {
×
1118
      this.context.warning(e.getMessage(), e);
×
1119
      return 0;
×
1120
    }
1121
  }
1122

1123
  private long getFileSizeRecursive(Path path) {
1124

1125
    long size = 0;
2✔
1126
    if (Files.isDirectory(path)) {
5✔
1127
      try (Stream<Path> childStream = Files.list(path)) {
3✔
1128
        Iterator<Path> iterator = childStream.iterator();
3✔
1129
        while (iterator.hasNext()) {
3✔
1130
          Path child = iterator.next();
4✔
1131
          size += getFileSizeRecursive(child);
6✔
1132
        }
1✔
1133
      } catch (IOException e) {
×
1134
        throw new RuntimeException("Failed to iterate children of folder " + path, e);
×
1135
      }
1✔
1136
    } else {
1137
      size += getFileSize(path);
6✔
1138
    }
1139
    return size;
2✔
1140
  }
1141

1142
  @Override
1143
  public Path findExistingFile(String fileName, List<Path> searchDirs) {
1144

1145
    for (Path dir : searchDirs) {
10!
1146
      Path filePath = dir.resolve(fileName);
4✔
1147
      try {
1148
        if (Files.exists(filePath)) {
5✔
1149
          return filePath;
2✔
1150
        }
1151
      } catch (Exception e) {
×
1152
        throw new IllegalStateException("Unexpected error while checking existence of file " + filePath + " .", e);
×
1153
      }
1✔
1154
    }
1✔
1155
    return null;
×
1156
  }
1157

1158
  @Override
1159
  public boolean setWritable(Path file, boolean writable) {
1160

1161
    try {
1162
      // POSIX
1163
      PosixFileAttributeView posix = Files.getFileAttributeView(file, PosixFileAttributeView.class);
7✔
1164
      if (posix != null) {
2!
1165
        Set<PosixFilePermission> permissions = new HashSet<>(posix.readAttributes().permissions());
7✔
1166
        boolean changed;
1167
        if (writable) {
2!
1168
          changed = permissions.add(PosixFilePermission.OWNER_WRITE);
5✔
1169
        } else {
1170
          changed = permissions.remove(PosixFilePermission.OWNER_WRITE);
×
1171
        }
1172
        if (changed) {
2!
1173
          posix.setPermissions(permissions);
×
1174
        }
1175
        return true;
2✔
1176
      }
1177

1178
      // Windows
1179
      DosFileAttributeView dos = Files.getFileAttributeView(file, DosFileAttributeView.class);
×
1180
      if (dos != null) {
×
1181
        dos.setReadOnly(!writable);
×
1182
        return true;
×
1183
      }
1184

1185
      this.context.debug("Failed to set writing permission for file {}", file);
×
1186
      return false;
×
1187

1188
    } catch (IOException e) {
1✔
1189
      this.context.debug("Error occurred when trying to set writing permission for file " + file + ": " + e);
8✔
1190
      return false;
2✔
1191
    }
1192
  }
1193

1194
  @Override
1195
  public void makeExecutable(Path path, boolean confirm) {
1196

1197
    if (Files.exists(path)) {
5✔
1198
      if (skipPermissionsIfWindows(path)) {
4!
1199
        return;
×
1200
      }
1201
      PathPermissions existingPermissions = getFilePermissions(path);
4✔
1202
      PathPermissions executablePermissions = existingPermissions.makeExecutable();
3✔
1203
      boolean update = (executablePermissions != existingPermissions);
7✔
1204
      if (update) {
2✔
1205
        if (confirm) {
2!
1206
          boolean yesContinue = this.context.question(
×
1207
              "We want to execute {} but this command seems to lack executable permissions!\n"
1208
                  + "Most probably the tool vendor did forget to add x-flags in the binary release package.\n"
1209
                  + "Before running the command, we suggest to set executable permissions to the file:\n"
1210
                  + "{}\n"
1211
                  + "For security reasons we ask for your confirmation so please check this request.\n"
1212
                  + "Changing permissions from {} to {}.\n"
1213
                  + "Do you confirm to make the command executable before running it?", path.getFileName(), path, existingPermissions, executablePermissions);
×
1214
          if (!yesContinue) {
×
1215
            return;
×
1216
          }
1217
        }
1218
        setFilePermissions(path, executablePermissions, false);
6✔
1219
      } else {
1220
        this.context.trace("Executable flags already present so no need to set them for file {}", path);
10✔
1221
      }
1222
    } else {
1✔
1223
      this.context.warning("Cannot set executable flag on file that does not exist: {}", path);
10✔
1224
    }
1225
  }
1✔
1226

1227
  @Override
1228
  public PathPermissions getFilePermissions(Path path) {
1229

1230
    PathPermissions pathPermissions;
1231
    String info = "";
2✔
1232
    if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
1233
      info = "mocked-";
×
1234
      if (Files.isDirectory(path)) {
×
1235
        pathPermissions = PathPermissions.MODE_RWX_RX_RX;
×
1236
      } else {
1237
        Path parent = path.getParent();
×
1238
        if ((parent != null) && (parent.getFileName().toString().equals("bin"))) {
×
1239
          pathPermissions = PathPermissions.MODE_RWX_RX_RX;
×
1240
        } else {
1241
          pathPermissions = PathPermissions.MODE_RW_R_R;
×
1242
        }
1243
      }
×
1244
    } else {
1245
      Set<PosixFilePermission> permissions;
1246
      try {
1247
        // Read the current file permissions
1248
        permissions = Files.getPosixFilePermissions(path);
5✔
1249
      } catch (IOException e) {
×
1250
        throw new RuntimeException("Failed to get permissions for " + path, e);
×
1251
      }
1✔
1252
      pathPermissions = PathPermissions.of(permissions);
3✔
1253
    }
1254
    this.context.trace("Read {}permissions of {} as {}.", info, path, pathPermissions);
18✔
1255
    return pathPermissions;
2✔
1256
  }
1257

1258
  @Override
1259
  public void setFilePermissions(Path path, PathPermissions permissions, boolean logErrorAndContinue) {
1260

1261
    if (skipPermissionsIfWindows(path)) {
4!
1262
      return;
×
1263
    }
1264
    try {
1265
      this.context.debug("Setting permissions for {} to {}", path, permissions);
14✔
1266
      // Set the new permissions
1267
      Files.setPosixFilePermissions(path, permissions.toPosix());
5✔
1268
    } catch (IOException e) {
×
1269
      if (logErrorAndContinue) {
×
1270
        this.context.warning().log(e, "Failed to set permissions to {} for path {}", permissions, path);
×
1271
      } else {
1272
        throw new RuntimeException("Failed to set permissions to " + permissions + " for path " + path, e);
×
1273
      }
1274
    }
1✔
1275
  }
1✔
1276

1277
  private boolean skipPermissionsIfWindows(Path path) {
1278

1279
    if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
1280
      this.context.trace("Windows does not have file permissions hence omitting for {}", path);
×
1281
      return true;
×
1282
    }
1283
    return false;
2✔
1284
  }
1285

1286
  @Override
1287
  public void touch(Path file) {
1288

1289
    if (Files.exists(file)) {
5✔
1290
      try {
1291
        Files.setLastModifiedTime(file, FileTime.fromMillis(System.currentTimeMillis()));
5✔
1292
      } catch (IOException e) {
×
1293
        throw new IllegalStateException("Could not update modification-time of " + file, e);
×
1294
      }
1✔
1295
    } else {
1296
      try {
1297
        Files.createFile(file);
5✔
1298
      } catch (IOException e) {
1✔
1299
        throw new IllegalStateException("Could not create empty file " + file, e);
8✔
1300
      }
1✔
1301
    }
1302
  }
1✔
1303

1304
  @Override
1305
  public String readFileContent(Path file) {
1306

1307
    this.context.trace("Reading content of file from {}", file);
10✔
1308
    if (!Files.exists((file))) {
5!
1309
      this.context.debug("File {} does not exist", file);
×
1310
      return null;
×
1311
    }
1312
    try {
1313
      String content = Files.readString(file);
3✔
1314
      this.context.trace("Completed reading {} character(s) from file {}", content.length(), file);
16✔
1315
      return content;
2✔
1316
    } catch (IOException e) {
×
1317
      throw new IllegalStateException("Failed to read file " + file, e);
×
1318
    }
1319
  }
1320

1321
  @Override
1322
  public void writeFileContent(String content, Path file, boolean createParentDir) {
1323

1324
    if (createParentDir) {
2✔
1325
      mkdirs(file.getParent());
4✔
1326
    }
1327
    if (content == null) {
2!
1328
      content = "";
×
1329
    }
1330
    this.context.trace("Writing content with {} character(s) to file {}", content.length(), file);
16✔
1331
    if (Files.exists(file)) {
5✔
1332
      this.context.info("Overriding content of file {}", file);
10✔
1333
    }
1334
    try {
1335
      Files.writeString(file, content);
6✔
1336
      this.context.trace("Wrote content to file {}", file);
10✔
1337
    } catch (IOException e) {
×
1338
      throw new RuntimeException("Failed to write file " + file, e);
×
1339
    }
1✔
1340
  }
1✔
1341

1342
  @Override
1343
  public List<String> readFileLines(Path file) {
1344

1345
    this.context.trace("Reading content of file from {}", file);
10✔
1346
    if (!Files.exists(file)) {
5✔
1347
      this.context.warning("File {} does not exist", file);
10✔
1348
      return null;
2✔
1349
    }
1350
    try {
1351
      List<String> content = Files.readAllLines(file);
3✔
1352
      this.context.trace("Completed reading {} lines from file {}", content.size(), file);
16✔
1353
      return content;
2✔
1354
    } catch (IOException e) {
×
1355
      throw new IllegalStateException("Failed to read file " + file, e);
×
1356
    }
1357
  }
1358

1359
  @Override
1360
  public void writeFileLines(List<String> content, Path file, boolean createParentDir) {
1361

1362
    if (createParentDir) {
2!
1363
      mkdirs(file.getParent());
×
1364
    }
1365
    if (content == null) {
2!
1366
      content = List.of();
×
1367
    }
1368
    this.context.trace("Writing content with {} lines to file {}", content.size(), file);
16✔
1369
    if (Files.exists(file)) {
5✔
1370
      this.context.debug("Overriding content of file {}", file);
10✔
1371
    }
1372
    try {
1373
      Files.write(file, content);
6✔
1374
      this.context.trace("Wrote content to file {}", file);
10✔
1375
    } catch (IOException e) {
×
1376
      throw new RuntimeException("Failed to write file " + file, e);
×
1377
    }
1✔
1378
  }
1✔
1379

1380
  @Override
1381
  public void readProperties(Path file, Properties properties) {
1382

1383
    try (Reader reader = Files.newBufferedReader(file)) {
3✔
1384
      properties.load(reader);
3✔
1385
      this.context.debug("Successfully loaded {} properties from {}", properties.size(), file);
16✔
1386
    } catch (IOException e) {
×
1387
      throw new IllegalStateException("Failed to read properties file: " + file, e);
×
1388
    }
1✔
1389
  }
1✔
1390

1391
  @Override
1392
  public void writeProperties(Properties properties, Path file, boolean createParentDir) {
1393

1394
    if (createParentDir) {
2✔
1395
      mkdirs(file.getParent());
4✔
1396
    }
1397
    try (Writer writer = Files.newBufferedWriter(file)) {
5✔
1398
      properties.store(writer, null); // do not get confused - Java still writes a date/time header that cannot be omitted
4✔
1399
      this.context.debug("Successfully saved {} properties to {}", properties.size(), file);
16✔
1400
    } catch (IOException e) {
×
1401
      throw new IllegalStateException("Failed to save properties file during tests.", e);
×
1402
    }
1✔
1403
  }
1✔
1404

1405
  @Override
1406
  public void readIniFile(Path file, IniFile iniFile) {
1407

1408
    if (!Files.exists(file)) {
5✔
1409
      this.context.debug("INI file {} does not exist.", iniFile);
10✔
1410
      return;
1✔
1411
    }
1412
    List<String> iniLines = readFileLines(file);
4✔
1413
    IniSection currentIniSection = iniFile.getInitialSection();
3✔
1414
    for (String line : iniLines) {
10✔
1415
      if (line.trim().startsWith("[")) {
5✔
1416
        currentIniSection = iniFile.getOrCreateSection(line);
5✔
1417
      } else if (line.isBlank() || IniComment.COMMENT_SYMBOLS.contains(line.trim().charAt(0))) {
11✔
1418
        currentIniSection.addComment(line);
4✔
1419
      } else {
1420
        int index = line.indexOf('=');
4✔
1421
        if (index > 0) {
2!
1422
          currentIniSection.setProperty(line);
3✔
1423
        }
1424
      }
1425
    }
1✔
1426
  }
1✔
1427

1428
  @Override
1429
  public void writeIniFile(IniFile iniFile, Path file, boolean createParentDir) {
1430

1431
    String iniString = iniFile.toString();
3✔
1432
    writeFileContent(iniString, file, createParentDir);
5✔
1433
  }
1✔
1434

1435
  @Override
1436
  public Duration getFileAge(Path path) {
1437

1438
    if (Files.exists(path)) {
5✔
1439
      try {
1440
        long currentTime = System.currentTimeMillis();
2✔
1441
        long fileModifiedTime = Files.getLastModifiedTime(path).toMillis();
6✔
1442
        return Duration.ofMillis(currentTime - fileModifiedTime);
5✔
1443
      } catch (IOException e) {
×
1444
        this.context.warning().log(e, "Could not get modification-time of {}.", path);
×
1445
      }
×
1446
    } else {
1447
      this.context.debug("Path {} is missing - skipping modification-time and file age check.", path);
10✔
1448
    }
1449
    return null;
2✔
1450
  }
1451

1452
  @Override
1453
  public boolean isFileAgeRecent(Path path, Duration cacheDuration) {
1454

1455
    Duration age = getFileAge(path);
4✔
1456
    if (age == null) {
2✔
1457
      return false;
2✔
1458
    }
1459
    this.context.debug("The path {} was last updated {} ago and caching duration is {}.", path, age, cacheDuration);
18✔
1460
    return (age.toMillis() <= cacheDuration.toMillis());
10✔
1461
  }
1462
}
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