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

devonfw / IDEasy / 21181339274

20 Jan 2026 05:35PM UTC coverage: 70.454% (-0.003%) from 70.457%
21181339274

Pull #1684

github

web-flow
Merge 28dd8d461 into c3912ae01
Pull Request #1684: #1683: fix NPE

4033 of 6310 branches covered (63.91%)

Branch coverage included in aggregate %.

10482 of 14292 relevant lines covered (73.34%)

3.18 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

866
  @Override
867
  public void compressTarGz(Path dir, OutputStream out) {
868

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1112
  private long getFileSize(Path file) {
1113

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

1122
  private long getFileSizeRecursive(Path path) {
1123

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1276
  private boolean skipPermissionsIfWindows(Path path) {
1277

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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