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

devonfw / IDEasy / 16452054488

22 Jul 2025 06:06PM UTC coverage: 68.445% (-0.02%) from 68.465%
16452054488

Pull #1419

github

web-flow
Merge 8f9431b8f into 31d427e63
Pull Request #1419: Fix Windows junction creation failure when broken junction exists

3288 of 5208 branches covered (63.13%)

Branch coverage included in aggregate %.

8412 of 11886 relevant lines covered (70.77%)

3.13 hits per line

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

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

47
import org.apache.commons.compress.archivers.ArchiveEntry;
48
import org.apache.commons.compress.archivers.ArchiveInputStream;
49
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
50
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
51
import org.jline.utils.Log;
52

53
import com.devonfw.tools.ide.cli.CliException;
54
import com.devonfw.tools.ide.cli.CliOfflineException;
55
import com.devonfw.tools.ide.context.IdeContext;
56
import com.devonfw.tools.ide.os.SystemInfoImpl;
57
import com.devonfw.tools.ide.process.ProcessContext;
58
import com.devonfw.tools.ide.util.DateTimeUtil;
59
import com.devonfw.tools.ide.util.FilenameUtil;
60
import com.devonfw.tools.ide.util.HexUtil;
61

62
/**
63
 * Implementation of {@link FileAccess}.
64
 */
65
public class FileAccessImpl implements FileAccess {
66

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

69
  private static final String WINDOWS_FILE_LOCK_WARNING =
70
      "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"
71
          + WINDOWS_FILE_LOCK_DOCUMENTATION_PAGE;
72

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

75
  private final IdeContext context;
76

77
  /**
78
   * The constructor.
79
   *
80
   * @param context the {@link IdeContext} to use.
81
   */
82
  public FileAccessImpl(IdeContext context) {
83

84
    super();
2✔
85
    this.context = context;
3✔
86
  }
1✔
87

88
  private HttpClient createHttpClient(String url) {
89

90
    HttpClient.Builder builder = HttpClient.newBuilder().followRedirects(Redirect.ALWAYS);
4✔
91
    return builder.build();
3✔
92
  }
93

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

97
    this.context.info("Trying to download {} from {}", target.getFileName(), url);
15✔
98
    mkdirs(target.getParent());
4✔
99
    try {
100
      if (this.context.isOffline()) {
4!
101
        throw CliOfflineException.ofDownloadViaUrl(url);
×
102
      }
103
      if (url.startsWith("http")) {
4✔
104

105
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)).GET().build();
7✔
106
        HttpClient client = createHttpClient(url);
4✔
107
        HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
5✔
108
        int statusCode = response.statusCode();
3✔
109
        if (statusCode == 200) {
3!
110
          downloadFileWithProgressBar(url, target, response);
6✔
111
        } else {
112
          throw new IllegalStateException("Download failed with status code " + statusCode);
×
113
        }
114
      } else if (url.startsWith("ftp") || url.startsWith("sftp")) {
9!
115
        throw new IllegalArgumentException("Unsupported download URL: " + url);
×
116
      } else {
117
        Path source = Path.of(url);
5✔
118
        if (isFile(source)) {
4!
119
          // network drive
120

121
          copyFileWithProgressBar(source, target);
5✔
122
        } else {
123
          throw new IllegalArgumentException("Download path does not point to a downloadable file: " + url);
×
124
        }
125
      }
126
    } catch (Exception e) {
×
127
      throw new IllegalStateException("Failed to download file from URL " + url + " to " + target, e);
×
128
    }
1✔
129
  }
1✔
130

131
  /**
132
   * Downloads a file while showing a {@link IdeProgressBar}.
133
   *
134
   * @param url the url to download.
135
   * @param target Path of the target directory.
136
   * @param response the {@link HttpResponse} to use.
137
   */
138
  private void downloadFileWithProgressBar(String url, Path target, HttpResponse<InputStream> response) {
139

140
    long contentLength = response.headers().firstValueAsLong("content-length").orElse(-1);
7✔
141
    informAboutMissingContentLength(contentLength, url);
4✔
142

143
    byte[] data = new byte[1024];
3✔
144
    boolean fileComplete = false;
2✔
145
    int count;
146

147
    try (InputStream body = response.body();
4✔
148
        FileOutputStream fileOutput = new FileOutputStream(target.toFile());
6✔
149
        BufferedOutputStream bufferedOut = new BufferedOutputStream(fileOutput, data.length);
7✔
150
        IdeProgressBar pb = this.context.newProgressBarForDownload(contentLength)) {
5✔
151
      while (!fileComplete) {
2✔
152
        count = body.read(data);
4✔
153
        if (count <= 0) {
2✔
154
          fileComplete = true;
3✔
155
        } else {
156
          bufferedOut.write(data, 0, count);
5✔
157
          pb.stepBy(count);
5✔
158
        }
159
      }
160

161
    } catch (Exception e) {
×
162
      throw new RuntimeException(e);
×
163
    }
1✔
164
  }
1✔
165

166
  /**
167
   * Copies a file while displaying a progress bar.
168
   *
169
   * @param source Path of file to copy.
170
   * @param target Path of target directory.
171
   */
172
  private void copyFileWithProgressBar(Path source, Path target) throws IOException {
173

174
    try (InputStream in = new FileInputStream(source.toFile()); OutputStream out = new FileOutputStream(target.toFile())) {
12✔
175
      long size = getFileSize(source);
4✔
176
      byte[] buf = new byte[1024];
3✔
177
      try (IdeProgressBar pb = this.context.newProgressbarForCopying(size)) {
5✔
178
        int readBytes;
179
        while ((readBytes = in.read(buf)) > 0) {
6✔
180
          out.write(buf, 0, readBytes);
5✔
181
          if (size > 0) {
4!
182
            pb.stepBy(readBytes);
5✔
183
          }
184
        }
185
      } catch (Exception e) {
×
186
        throw new RuntimeException(e);
×
187
      }
1✔
188
    }
189
  }
1✔
190

191
  private void informAboutMissingContentLength(long contentLength, String url) {
192

193
    if (contentLength < 0) {
4✔
194
      this.context.warning("Content-Length was not provided by download from {}", url);
10✔
195
    }
196
  }
1✔
197

198
  @Override
199
  public void mkdirs(Path directory) {
200

201
    if (Files.isDirectory(directory)) {
5✔
202
      return;
1✔
203
    }
204
    this.context.trace("Creating directory {}", directory);
10✔
205
    try {
206
      Files.createDirectories(directory);
5✔
207
    } catch (IOException e) {
×
208
      throw new IllegalStateException("Failed to create directory " + directory, e);
×
209
    }
1✔
210
  }
1✔
211

212
  @Override
213
  public boolean isFile(Path file) {
214

215
    if (!Files.exists(file)) {
5!
216
      this.context.trace("File {} does not exist", file);
×
217
      return false;
×
218
    }
219
    if (Files.isDirectory(file)) {
5!
220
      this.context.trace("Path {} is a directory but a regular file was expected", file);
×
221
      return false;
×
222
    }
223
    return true;
2✔
224
  }
225

226
  @Override
227
  public boolean isExpectedFolder(Path folder) {
228

229
    if (Files.isDirectory(folder)) {
5✔
230
      return true;
2✔
231
    }
232
    this.context.warning("Expected folder was not found at {}", folder);
10✔
233
    return false;
2✔
234
  }
235

236
  @Override
237
  public String checksum(Path file, String hashAlgorithm) {
238

239
    MessageDigest md;
240
    try {
241
      md = MessageDigest.getInstance(hashAlgorithm);
×
242
    } catch (NoSuchAlgorithmException e) {
×
243
      throw new IllegalStateException("No such hash algorithm " + hashAlgorithm, e);
×
244
    }
×
245
    byte[] buffer = new byte[1024];
×
246
    try (InputStream is = Files.newInputStream(file); DigestInputStream dis = new DigestInputStream(is, md)) {
×
247
      int read = 0;
×
248
      while (read >= 0) {
×
249
        read = dis.read(buffer);
×
250
      }
251
    } catch (Exception e) {
×
252
      throw new IllegalStateException("Failed to read and hash file " + file, e);
×
253
    }
×
254
    byte[] digestBytes = md.digest();
×
255
    return HexUtil.toHexString(digestBytes);
×
256
  }
257

258
  public boolean isJunction(Path path) {
259

260
    if (!SystemInfoImpl.INSTANCE.isWindows()) {
3!
261
      return false;
2✔
262
    }
263

264
    try {
265
      BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
×
266
      return attr.isOther() && attr.isDirectory();
×
267
    } catch (NoSuchFileException e) {
×
268
      return false; // file doesn't exist
×
269
    } catch (IOException e) {
×
270
      // For broken junctions, reading attributes might fail with various IOExceptions.
271
      // In such cases, we should check if the path exists without following links.
272
      // If it exists but we can't read its attributes, it's likely a broken junction.
273
      if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
×
274
        this.context.debug("Path " + path + " exists but attributes cannot be read, likely a broken junction: " + e.getMessage());
×
275
        return true; // Assume it's a broken junction
×
276
      }
277
      // If it doesn't exist at all, it's not a junction
278
      return false;
×
279
    }
280
  }
281

282
  @Override
283
  public Path backup(Path fileOrFolder) {
284

285
    if ((fileOrFolder != null) && (Files.isSymbolicLink(fileOrFolder) || isJunction(fileOrFolder))) {
9!
286
      delete(fileOrFolder);
4✔
287
    } else if ((fileOrFolder != null) && Files.exists(fileOrFolder)) {
7!
288
      LocalDateTime now = LocalDateTime.now();
2✔
289
      String date = DateTimeUtil.formatDate(now, true);
4✔
290
      String time = DateTimeUtil.formatTime(now);
3✔
291
      String filename = fileOrFolder.getFileName().toString();
4✔
292
      Path backupPath = this.context.getIdeHome().resolve(IdeContext.FOLDER_BACKUPS).resolve(date).resolve(time + "_" + filename);
12✔
293
      backupPath = appendParentPath(backupPath, fileOrFolder.getParent(), 2);
6✔
294
      mkdirs(backupPath);
3✔
295
      Path target = backupPath.resolve(filename);
4✔
296
      this.context.info("Creating backup by moving {} to {}", fileOrFolder, target);
14✔
297
      move(fileOrFolder, target);
6✔
298
      return target;
2✔
299
    } else {
300
      this.context.trace("Backup of {} skipped as the path does not exist.", fileOrFolder);
10✔
301
    }
302
    return fileOrFolder;
2✔
303
  }
304

305
  private static Path appendParentPath(Path path, Path parent, int max) {
306

307
    if ((parent == null) || (max <= 0)) {
4!
308
      return path;
2✔
309
    }
310
    return appendParentPath(path, parent.getParent(), max - 1).resolve(parent.getFileName());
11✔
311
  }
312

313
  @Override
314
  public void move(Path source, Path targetDir, StandardCopyOption... copyOptions) {
315

316
    this.context.trace("Moving {} to {}", source, targetDir);
14✔
317
    try {
318
      Files.move(source, targetDir, copyOptions);
5✔
319
    } catch (IOException e) {
×
320
      String fileType = Files.isSymbolicLink(source) ? "symlink" : isJunction(source) ? "junction" : Files.isDirectory(source) ? "directory" : "file";
×
321
      String message = "Failed to move " + fileType + ": " + source + " to " + targetDir + ".";
×
322
      if (this.context.getSystemInfo().isWindows()) {
×
323
        message = message + "\n" + WINDOWS_FILE_LOCK_WARNING;
×
324
      }
325
      throw new IllegalStateException(message, e);
×
326
    }
1✔
327
  }
1✔
328

329
  @Override
330
  public void copy(Path source, Path target, FileCopyMode mode, PathCopyListener listener) {
331

332
    if (mode != FileCopyMode.COPY_TREE_CONTENT) {
3✔
333
      // if we want to copy the file or folder "source" to the existing folder "target" in a shell this will copy
334
      // source into that folder so that we as a result have a copy in "target/source".
335
      // With Java NIO the raw copy method will fail as we cannot copy "source" to the path of the "target" folder.
336
      // For folders we want the same behavior as the linux "cp -r" command so that the "source" folder is copied
337
      // and not only its content what also makes it consistent with the move method that also behaves this way.
338
      // Therefore we need to add the filename (foldername) of "source" to the "target" path before.
339
      // For the rare cases, where we want to copy the content of a folder (cp -r source/* target) we support
340
      // it via the COPY_TREE_CONTENT mode.
341
      Path fileName = source.getFileName();
3✔
342
      if (fileName != null) { // if filename is null, we are copying the root of a (virtual filesystem)
2✔
343
        target = target.resolve(fileName.toString());
5✔
344
      }
345
    }
346
    boolean fileOnly = mode.isFileOnly();
3✔
347
    String operation = mode.getOperation();
3✔
348
    if (mode.isExtract()) {
3✔
349
      this.context.debug("Starting to {} to {}", operation, target);
15✔
350
    } else {
351
      if (fileOnly) {
2✔
352
        this.context.debug("Starting to {} file {} to {}", operation, source, target);
19✔
353
      } else {
354
        this.context.debug("Starting to {} {} recursively to {}", operation, source, target);
18✔
355
      }
356
    }
357
    if (fileOnly && Files.isDirectory(source)) {
7!
358
      throw new IllegalStateException("Expected file but found a directory to copy at " + source);
×
359
    }
360
    if (mode.isFailIfExists()) {
3✔
361
      if (Files.exists(target)) {
5!
362
        throw new IllegalStateException("Failed to " + operation + " " + source + " to already existing target " + target);
×
363
      }
364
    } else if (mode == FileCopyMode.COPY_TREE_OVERRIDE_TREE) {
3✔
365
      delete(target);
3✔
366
    }
367
    try {
368
      copyRecursive(source, target, mode, listener);
6✔
369
    } catch (IOException e) {
×
370
      throw new IllegalStateException("Failed to " + operation + " " + source + " to " + target, e);
×
371
    }
1✔
372
  }
1✔
373

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

376
    if (Files.isDirectory(source)) {
5✔
377
      mkdirs(target);
3✔
378
      try (Stream<Path> childStream = Files.list(source)) {
3✔
379
        Iterator<Path> iterator = childStream.iterator();
3✔
380
        while (iterator.hasNext()) {
3✔
381
          Path child = iterator.next();
4✔
382
          copyRecursive(child, target.resolve(child.getFileName().toString()), mode, listener);
10✔
383
        }
1✔
384
      }
385
      listener.onCopy(source, target, true);
6✔
386
    } else if (Files.exists(source)) {
5!
387
      if (mode.isOverrideFile()) {
3✔
388
        delete(target);
3✔
389
      }
390
      this.context.trace("Starting to {} {} to {}", mode.getOperation(), source, target);
19✔
391
      Files.copy(source, target);
6✔
392
      listener.onCopy(source, target, false);
6✔
393
    } else {
394
      throw new IOException("Path " + source + " does not exist.");
×
395
    }
396
  }
1✔
397

398
  /**
399
   * 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
400
   * {@link Path} that is neither a symbolic link nor a Windows junction.
401
   *
402
   * @param path the {@link Path} to delete.
403
   * @throws IOException if the actual {@link Files#delete(Path) deletion} fails.
404
   */
405
  private void deleteLinkIfExists(Path path) throws IOException {
406

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

410
    assert !(isSymlink && isJunction);
5!
411

412
    if (isJunction || isSymlink) {
4!
413
      this.context.info("Deleting previous " + (isJunction ? "junction" : "symlink") + " at " + path);
9!
414
      Files.delete(path);
2✔
415
    }
416
  }
1✔
417

418
  /**
419
   * Adapts the given {@link Path} to be relative or absolute depending on the given {@code relative} flag. Additionally, {@link Path#toRealPath(LinkOption...)}
420
   * is applied to {@code source}.
421
   *
422
   * @param source the {@link Path} to adapt.
423
   * @param targetLink the {@link Path} used to calculate the relative path to the {@code source} if {@code relative} is set to {@code true}.
424
   * @param relative the {@code relative} flag.
425
   * @return the adapted {@link Path}.
426
   * @see FileAccessImpl#symlink(Path, Path, boolean)
427
   */
428
  private Path adaptPath(Path source, Path targetLink, boolean relative) throws IOException {
429

430
    if (source.isAbsolute()) {
3✔
431
      try {
432
        source = source.toRealPath(LinkOption.NOFOLLOW_LINKS); // to transform ../d1/../d2 to ../d2
9✔
433
      } catch (IOException e) {
×
434
        throw new IOException("Calling toRealPath() on the source (" + source + ") in method FileAccessImpl.adaptPath() failed.", e);
×
435
      }
1✔
436
      if (relative) {
2✔
437
        source = targetLink.getParent().relativize(source);
5✔
438
        // to make relative links like this work: dir/link -> dir
439
        source = (source.toString().isEmpty()) ? Path.of(".") : source;
12✔
440
      }
441
    } else { // source is relative
442
      if (relative) {
2✔
443
        // even though the source is already relative, toRealPath should be called to transform paths like
444
        // this ../d1/../d2 to ../d2
445
        source = targetLink.getParent().relativize(targetLink.resolveSibling(source).toRealPath(LinkOption.NOFOLLOW_LINKS));
14✔
446
        source = (source.toString().isEmpty()) ? Path.of(".") : source;
12✔
447
      } else { // !relative
448
        try {
449
          source = targetLink.resolveSibling(source).toRealPath(LinkOption.NOFOLLOW_LINKS);
11✔
450
        } catch (IOException e) {
×
451
          throw new IOException("Calling toRealPath() on " + targetLink + ".resolveSibling(" + source + ") in method FileAccessImpl.adaptPath() failed.", e);
×
452
        }
1✔
453
      }
454
    }
455
    return source;
2✔
456
  }
457

458
  /**
459
   * Creates a Windows junction at {@code targetLink} pointing to {@code source}.
460
   *
461
   * @param source must be another Windows junction or a directory.
462
   * @param targetLink the location of the Windows junction.
463
   */
464
  private void createWindowsJunction(Path source, Path targetLink) {
465

466
    this.context.trace("Creating a Windows junction at " + targetLink + " with " + source + " as source.");
×
467
    Path fallbackPath;
468
    if (!source.isAbsolute()) {
×
469
      this.context.warning("You are on Windows and you do not have permissions to create symbolic links. Junctions are used as an "
×
470
          + "alternative, however, these can not point to relative paths. So the source (" + source + ") is interpreted as an absolute path.");
471
      try {
472
        fallbackPath = targetLink.resolveSibling(source).toRealPath(LinkOption.NOFOLLOW_LINKS);
×
473
      } catch (IOException e) {
×
474
        throw new IllegalStateException(
×
475
            "Since Windows junctions are used, the source must be an absolute path. The transformation of the passed " + "source (" + source
476
                + ") to an absolute path failed.", e);
477
      }
×
478

479
    } else {
480
      fallbackPath = source;
×
481
    }
482
    if (!Files.isDirectory(fallbackPath)) { // if source is a junction. This returns true as well.
×
483
      throw new IllegalStateException(
×
484
          "These junctions can only point to directories or other junctions. Please make sure that the source (" + fallbackPath + ") is one of these.");
485
    }
486
    this.context.newProcess().executable("cmd").addArgs("/c", "mklink", "/d", "/j", targetLink.toString(), fallbackPath.toString()).run();
×
487
  }
×
488

489
  @Override
490
  public void symlink(Path source, Path targetLink, boolean relative) {
491

492
    Path adaptedSource = null;
2✔
493
    try {
494
      adaptedSource = adaptPath(source, targetLink, relative);
6✔
495
    } catch (IOException e) {
×
496
      throw new IllegalStateException("Failed to adapt source for source (" + source + ") target (" + targetLink + ") and relative (" + relative + ")", e);
×
497
    }
1✔
498
    this.context.debug("Creating {} symbolic link {} pointing to {}", adaptedSource.isAbsolute() ? "" : "relative", targetLink, adaptedSource);
23✔
499

500
    try {
501
      deleteLinkIfExists(targetLink);
3✔
502
    } catch (IOException e) {
×
503
      throw new IllegalStateException("Failed to delete previous symlink or Windows junction at " + targetLink, e);
×
504
    }
1✔
505

506
    try {
507
      Files.createSymbolicLink(targetLink, adaptedSource);
6✔
508
    } catch (FileSystemException e) {
×
509
      if (SystemInfoImpl.INSTANCE.isWindows()) {
×
510
        this.context.info("Due to lack of permissions, Microsoft's mklink with junction had to be used to create "
×
511
            + "a Symlink. See https://github.com/devonfw/IDEasy/blob/main/documentation/symlink.adoc for " + "further details. Error was: "
512
            + e.getMessage());
×
513
        createWindowsJunction(adaptedSource, targetLink);
×
514
      } else {
515
        throw new RuntimeException(e);
×
516
      }
517
    } catch (IOException e) {
×
518
      throw new IllegalStateException(
×
519
          "Failed to create a " + (adaptedSource.isAbsolute() ? "" : "relative") + "symbolic link " + targetLink + " pointing to " + source, e);
×
520
    }
1✔
521
  }
1✔
522

523
  @Override
524
  public Path toRealPath(Path path) {
525

526
    return toRealPath(path, true);
5✔
527
  }
528

529
  @Override
530
  public Path toCanonicalPath(Path path) {
531

532
    return toRealPath(path, false);
5✔
533
  }
534

535
  private Path toRealPath(Path path, boolean resolveLinks) {
536

537
    try {
538
      Path realPath;
539
      if (resolveLinks) {
2✔
540
        realPath = path.toRealPath();
6✔
541
      } else {
542
        realPath = path.toRealPath(LinkOption.NOFOLLOW_LINKS);
9✔
543
      }
544
      if (!realPath.equals(path)) {
4✔
545
        this.context.trace("Resolved path {} to {}", path, realPath);
14✔
546
      }
547
      return realPath;
2✔
548
    } catch (IOException e) {
×
549
      throw new IllegalStateException("Failed to get real path for " + path, e);
×
550
    }
551
  }
552

553
  @Override
554
  public Path createTempDir(String name) {
555

556
    try {
557
      Path tmp = this.context.getTempPath();
4✔
558
      Path tempDir = tmp.resolve(name);
4✔
559
      int tries = 1;
2✔
560
      while (Files.exists(tempDir)) {
5!
561
        long id = System.nanoTime() & 0xFFFF;
×
562
        tempDir = tmp.resolve(name + "-" + id);
×
563
        tries++;
×
564
        if (tries > 200) {
×
565
          throw new IOException("Unable to create unique name!");
×
566
        }
567
      }
×
568
      return Files.createDirectory(tempDir);
5✔
569
    } catch (IOException e) {
×
570
      throw new IllegalStateException("Failed to create temporary directory with prefix '" + name + "'!", e);
×
571
    }
572
  }
573

574
  @Override
575
  public void extract(Path archiveFile, Path targetDir, Consumer<Path> postExtractHook, boolean extract) {
576

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

617
  private void postExtractHook(Consumer<Path> postExtractHook, Path properInstallDir) {
618

619
    if (postExtractHook != null) {
2✔
620
      postExtractHook.accept(properInstallDir);
3✔
621
    }
622
  }
1✔
623

624
  /**
625
   * @param path the {@link Path} to start the recursive search from.
626
   * @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
627
   *     item in their respective directory and {@code s} is not named "bin".
628
   */
629
  private Path getProperInstallationSubDirOf(Path path, Path archiveFile) {
630

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

648
  @Override
649
  public void extractZip(Path file, Path targetDir) {
650

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

668
  @SuppressWarnings("unchecked")
669
  private void onFileCopiedFromZip(Path source, Path target, boolean directory, IdeProgressBar progressBar) {
670

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

687
  @Override
688
  public void extractTar(Path file, Path targetDir, TarCompression compression) {
689

690
    extractArchive(file, targetDir, in -> new TarArchiveInputStream(compression.unpack(in)));
13✔
691
  }
1✔
692

693
  @Override
694
  public void extractJar(Path file, Path targetDir) {
695

696
    extractZip(file, targetDir);
4✔
697
  }
1✔
698

699
  /**
700
   * @param permissions The integer as returned by {@link TarArchiveEntry#getMode()} that represents the file permissions of a file on a Unix file system.
701
   * @return A String representing the file permissions. E.g. "rwxrwxr-x" or "rw-rw-r--"
702
   */
703
  public static String generatePermissionString(int permissions) {
704

705
    // Ensure that only the last 9 bits are considered
706
    permissions &= 0b111111111;
4✔
707

708
    StringBuilder permissionStringBuilder = new StringBuilder("rwxrwxrwx");
5✔
709
    for (int i = 0; i < 9; i++) {
7✔
710
      int mask = 1 << i;
4✔
711
      char currentChar = ((permissions & mask) != 0) ? permissionStringBuilder.charAt(8 - i) : '-';
12✔
712
      permissionStringBuilder.setCharAt(8 - i, currentChar);
6✔
713
    }
714

715
    return permissionStringBuilder.toString();
3✔
716
  }
717

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

720
    this.context.info("Extracting TAR file {} to {}", file, targetDir);
14✔
721
    try (InputStream is = Files.newInputStream(file);
5✔
722
        ArchiveInputStream<?> ais = unpacker.apply(is);
5✔
723
        IdeProgressBar pb = this.context.newProgressbarForExtracting(getFileSize(file))) {
7✔
724

725
      ArchiveEntry entry = ais.getNextEntry();
3✔
726
      boolean isTar = ais instanceof TarArchiveInputStream;
3✔
727
      while (entry != null) {
2✔
728
        String permissionStr = null;
2✔
729
        if (isTar) {
2!
730
          int tarMode = ((TarArchiveEntry) entry).getMode();
4✔
731
          permissionStr = generatePermissionString(tarMode);
3✔
732
        }
733
        Path entryName = Path.of(entry.getName());
6✔
734
        Path entryPath = targetDir.resolve(entryName).toAbsolutePath();
5✔
735
        if (!entryPath.startsWith(targetDir)) {
4!
736
          throw new IOException("Preventing path traversal attack from " + entryName + " to " + entryPath);
×
737
        }
738
        if (entry.isDirectory()) {
3✔
739
          mkdirs(entryPath);
4✔
740
        } else {
741
          // ensure the file can also be created if directory entry was missing or out of order...
742
          mkdirs(entryPath.getParent());
4✔
743
          Files.copy(ais, entryPath);
6✔
744
        }
745
        if (isTar && !this.context.getSystemInfo().isWindows()) {
7!
746
          Set<PosixFilePermission> permissions = PosixFilePermissions.fromString(permissionStr);
3✔
747
          Files.setPosixFilePermissions(entryPath, permissions);
4✔
748
        }
749
        pb.stepBy(entry.getSize());
4✔
750
        entry = ais.getNextEntry();
3✔
751
      }
1✔
752
    } catch (IOException e) {
×
753
      throw new IllegalStateException("Failed to extract " + file + " to " + targetDir, e);
×
754
    }
1✔
755
  }
1✔
756

757
  @Override
758
  public void extractDmg(Path file, Path targetDir) {
759

760
    this.context.info("Extracting DMG file {} to {}", file, targetDir);
×
761
    assert this.context.getSystemInfo().isMac();
×
762

763
    Path mountPath = this.context.getIdeHome().resolve(IdeContext.FOLDER_UPDATES).resolve(IdeContext.FOLDER_VOLUME);
×
764
    mkdirs(mountPath);
×
765
    ProcessContext pc = this.context.newProcess();
×
766
    pc.executable("hdiutil");
×
767
    pc.addArgs("attach", "-quiet", "-nobrowse", "-mountpoint", mountPath, file);
×
768
    pc.run();
×
769
    Path appPath = findFirst(mountPath, p -> p.getFileName().toString().endsWith(".app"), false);
×
770
    if (appPath == null) {
×
771
      throw new IllegalStateException("Failed to unpack DMG as no MacOS *.app was found in file " + file);
×
772
    }
773

774
    copy(appPath, targetDir, FileCopyMode.COPY_TREE_OVERRIDE_TREE);
×
775
    pc.addArgs("detach", "-force", mountPath);
×
776
    pc.run();
×
777
  }
×
778

779
  @Override
780
  public void extractMsi(Path file, Path targetDir) {
781

782
    this.context.info("Extracting MSI file {} to {}", file, targetDir);
×
783
    this.context.newProcess().executable("msiexec").addArgs("/a", file, "/qn", "TARGETDIR=" + targetDir).run();
×
784
    // msiexec also creates a copy of the MSI
785
    Path msiCopy = targetDir.resolve(file.getFileName());
×
786
    delete(msiCopy);
×
787
  }
×
788

789
  @Override
790
  public void extractPkg(Path file, Path targetDir) {
791

792
    this.context.info("Extracting PKG file {} to {}", file, targetDir);
×
793
    Path tmpDirPkg = createTempDir("ide-pkg-");
×
794
    ProcessContext pc = this.context.newProcess();
×
795
    // we might also be able to use cpio from commons-compression instead of external xar...
796
    pc.executable("xar").addArgs("-C", tmpDirPkg, "-xf", file).run();
×
797
    Path contentPath = findFirst(tmpDirPkg, p -> p.getFileName().toString().equals("Payload"), true);
×
798
    extractTar(contentPath, targetDir, TarCompression.GZ);
×
799
    delete(tmpDirPkg);
×
800
  }
×
801

802
  @Override
803
  public void delete(Path path) {
804

805
    if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
9✔
806
      this.context.trace("Deleting {} skipped as the path does not exist.", path);
10✔
807
      return;
1✔
808
    }
809
    this.context.debug("Deleting {} ...", path);
10✔
810
    try {
811
      if (Files.isSymbolicLink(path) || isJunction(path)) {
7!
812
        Files.delete(path);
3✔
813
      } else {
814
        deleteRecursive(path);
3✔
815
      }
816
    } catch (IOException e) {
×
817
      throw new IllegalStateException("Failed to delete " + path, e);
×
818
    }
1✔
819
  }
1✔
820

821
  private void deleteRecursive(Path path) throws IOException {
822

823
    if (Files.isDirectory(path)) {
5✔
824
      try (Stream<Path> childStream = Files.list(path)) {
3✔
825
        Iterator<Path> iterator = childStream.iterator();
3✔
826
        while (iterator.hasNext()) {
3✔
827
          Path child = iterator.next();
4✔
828
          deleteRecursive(child);
3✔
829
        }
1✔
830
      }
831
    }
832
    this.context.trace("Deleting {} ...", path);
10✔
833
    boolean isSetWritable = setWritable(path, true);
5✔
834
    if (!isSetWritable) {
2✔
835
      this.context.debug("Couldn't give write access to file: " + path);
6✔
836
    }
837
    Files.delete(path);
2✔
838
  }
1✔
839

840
  @Override
841
  public Path findFirst(Path dir, Predicate<Path> filter, boolean recursive) {
842

843
    try {
844
      if (!Files.isDirectory(dir)) {
5✔
845
        return null;
2✔
846
      }
847
      return findFirstRecursive(dir, filter, recursive);
6✔
848
    } catch (IOException e) {
×
849
      throw new IllegalStateException("Failed to search for file in " + dir, e);
×
850
    }
851
  }
852

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

855
    List<Path> folders = null;
2✔
856
    try (Stream<Path> childStream = Files.list(dir)) {
3✔
857
      Iterator<Path> iterator = childStream.iterator();
3✔
858
      while (iterator.hasNext()) {
3✔
859
        Path child = iterator.next();
4✔
860
        if (filter.test(child)) {
4✔
861
          return child;
4✔
862
        } else if (recursive && Files.isDirectory(child)) {
2!
863
          if (folders == null) {
×
864
            folders = new ArrayList<>();
×
865
          }
866
          folders.add(child);
×
867
        }
868
      }
1✔
869
    }
4!
870
    if (folders != null) {
2!
871
      for (Path child : folders) {
×
872
        Path match = findFirstRecursive(child, filter, recursive);
×
873
        if (match != null) {
×
874
          return match;
×
875
        }
876
      }
×
877
    }
878
    return null;
2✔
879
  }
880

881
  @Override
882
  public List<Path> listChildrenMapped(Path dir, Function<Path, Path> filter) {
883

884
    if (!Files.isDirectory(dir)) {
5✔
885
      return List.of();
2✔
886
    }
887
    List<Path> children = new ArrayList<>();
4✔
888
    try (Stream<Path> childStream = Files.list(dir)) {
3✔
889
      Iterator<Path> iterator = childStream.iterator();
3✔
890
      while (iterator.hasNext()) {
3✔
891
        Path child = iterator.next();
4✔
892
        Path filteredChild = filter.apply(child);
5✔
893
        if (filteredChild != null) {
2✔
894
          if (filteredChild == child) {
3!
895
            this.context.trace("Accepted file {}", child);
11✔
896
          } else {
897
            this.context.trace("Accepted file {} and mapped to {}", child, filteredChild);
×
898
          }
899
          children.add(filteredChild);
5✔
900
        } else {
901
          this.context.trace("Ignoring file {} according to filter", child);
10✔
902
        }
903
      }
1✔
904
    } catch (IOException e) {
×
905
      throw new IllegalStateException("Failed to find children of directory " + dir, e);
×
906
    }
1✔
907
    return children;
2✔
908
  }
909

910
  @Override
911
  public boolean isEmptyDir(Path dir) {
912

913
    return listChildren(dir, f -> true).isEmpty();
8✔
914
  }
915

916
  private long getFileSize(Path file) {
917

918
    try {
919
      return Files.size(file);
3✔
920
    } catch (IOException e) {
×
921
      this.context.warning(e.getMessage(), e);
×
922
      return 0;
×
923
    }
924
  }
925

926
  private long getFileSizeRecursive(Path path) {
927

928
    long size = 0;
2✔
929
    if (Files.isDirectory(path)) {
5✔
930
      try (Stream<Path> childStream = Files.list(path)) {
3✔
931
        Iterator<Path> iterator = childStream.iterator();
3✔
932
        while (iterator.hasNext()) {
3✔
933
          Path child = iterator.next();
4✔
934
          size += getFileSizeRecursive(child);
6✔
935
        }
1✔
936
      } catch (IOException e) {
×
937
        throw new RuntimeException("Failed to iterate children of folder " + path, e);
×
938
      }
1✔
939
    } else {
940
      size += getFileSize(path);
6✔
941
    }
942
    return size;
2✔
943
  }
944

945
  @Override
946
  public Path findExistingFile(String fileName, List<Path> searchDirs) {
947

948
    for (Path dir : searchDirs) {
10!
949
      Path filePath = dir.resolve(fileName);
4✔
950
      try {
951
        if (Files.exists(filePath)) {
5✔
952
          return filePath;
2✔
953
        }
954
      } catch (Exception e) {
×
955
        throw new IllegalStateException("Unexpected error while checking existence of file " + filePath + " .", e);
×
956
      }
1✔
957
    }
1✔
958
    return null;
×
959
  }
960

961
  @Override
962
  public boolean setWritable(Path file, boolean writable) {
963
    try {
964
      // POSIX
965
      PosixFileAttributeView posix = Files.getFileAttributeView(file, PosixFileAttributeView.class);
7✔
966
      if (posix != null) {
2!
967
        Set<PosixFilePermission> permissions = new HashSet<>(posix.readAttributes().permissions());
7✔
968
        boolean changed;
969
        if (writable) {
2!
970
          changed = permissions.add(PosixFilePermission.OWNER_WRITE);
5✔
971
        } else {
972
          changed = permissions.remove(PosixFilePermission.OWNER_WRITE);
×
973
        }
974
        if (changed) {
2!
975
          posix.setPermissions(permissions);
×
976
        }
977
        return true;
2✔
978
      }
979

980
      // Windows
981
      DosFileAttributeView dos = Files.getFileAttributeView(file, DosFileAttributeView.class);
×
982
      if (dos != null) {
×
983
        dos.setReadOnly(!writable);
×
984
        return true;
×
985
      }
986

987
      this.context.debug("Failed to set writing permission for file {}", file);
×
988
      return false;
×
989

990
    } catch (IOException e) {
1✔
991
      this.context.debug("Error occurred when trying to set writing permission for file " + file + ": " + e);
8✔
992
      return false;
2✔
993
    }
994
  }
995

996
  @Override
997
  public void makeExecutable(Path file, boolean confirm) {
998

999
    if (Files.exists(file)) {
5✔
1000
      if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
1001
        this.context.trace("Windows does not have executable flags hence omitting for file {}", file);
×
1002
        return;
×
1003
      }
1004
      try {
1005
        // Read the current file permissions
1006
        Set<PosixFilePermission> existingPermissions = Files.getPosixFilePermissions(file);
5✔
1007

1008
        // Add execute permission for all users
1009
        Set<PosixFilePermission> executablePermissions = new HashSet<>(existingPermissions);
5✔
1010
        boolean update = false;
2✔
1011
        update |= executablePermissions.add(PosixFilePermission.OWNER_EXECUTE);
6✔
1012
        update |= executablePermissions.add(PosixFilePermission.GROUP_EXECUTE);
6✔
1013
        update |= executablePermissions.add(PosixFilePermission.OTHERS_EXECUTE);
6✔
1014

1015
        if (update) {
2✔
1016
          if (confirm) {
2!
1017
            boolean yesContinue = this.context.question(
×
1018
                "We want to execute " + file.getFileName() + " but this command seems to lack executable permissions!\n"
×
1019
                    + "Most probably the tool vendor did forgot to add x-flags in the binary release package.\n"
1020
                    + "Before running the command, we suggest to set executable permissions to the file:\n"
1021
                    + file + "\n"
1022
                    + "For security reasons we ask for your confirmation so please check this request.\n"
1023
                    + "Changing permissions from " + PosixFilePermissions.toString(existingPermissions) + " to " + PosixFilePermissions.toString(
×
1024
                    executablePermissions) + ".\n"
1025
                    + "Do you confirm to make the command executable before running it?");
1026
            if (!yesContinue) {
×
1027
              return;
×
1028
            }
1029
          }
1030
          this.context.debug("Setting executable flags for file {}", file);
10✔
1031
          // Set the new permissions
1032
          Files.setPosixFilePermissions(file, executablePermissions);
5✔
1033
        } else {
1034
          this.context.trace("Executable flags already present so no need to set them for file {}", file);
10✔
1035
        }
1036
      } catch (IOException e) {
×
1037
        throw new RuntimeException(e);
×
1038
      }
1✔
1039
    } else {
1040
      this.context.warning("Cannot set executable flag on file that does not exist: {}", file);
10✔
1041
    }
1042
  }
1✔
1043

1044
  @Override
1045
  public void touch(Path file) {
1046

1047
    if (Files.exists(file)) {
5✔
1048
      try {
1049
        Files.setLastModifiedTime(file, FileTime.fromMillis(System.currentTimeMillis()));
5✔
1050
      } catch (IOException e) {
×
1051
        throw new IllegalStateException("Could not update modification-time of " + file, e);
×
1052
      }
1✔
1053
    } else {
1054
      try {
1055
        Files.createFile(file);
5✔
1056
      } catch (IOException e) {
1✔
1057
        throw new IllegalStateException("Could not create empty file " + file, e);
8✔
1058
      }
1✔
1059
    }
1060
  }
1✔
1061

1062
  @Override
1063
  public String readFileContent(Path file) {
1064

1065
    this.context.trace("Reading content of file from {}", file);
10✔
1066
    if (!Files.exists((file))) {
5!
1067
      this.context.debug("File {} does not exist", file);
×
1068
      return null;
×
1069
    }
1070
    try {
1071
      String content = Files.readString(file);
3✔
1072
      this.context.trace("Completed reading {} character(s) from file {}", content.length(), file);
16✔
1073
      return content;
2✔
1074
    } catch (IOException e) {
×
1075
      throw new IllegalStateException("Failed to read file " + file, e);
×
1076
    }
1077
  }
1078

1079
  @Override
1080
  public void writeFileContent(String content, Path file, boolean createParentDir) {
1081

1082
    if (createParentDir) {
2✔
1083
      mkdirs(file.getParent());
4✔
1084
    }
1085
    if (content == null) {
2!
1086
      content = "";
×
1087
    }
1088
    this.context.trace("Writing content with {} character(s) to file {}", content.length(), file);
16✔
1089
    if (Files.exists(file)) {
5✔
1090
      this.context.info("Overriding content of file {}", file);
10✔
1091
    }
1092
    try {
1093
      Files.writeString(file, content);
6✔
1094
      this.context.trace("Wrote content to file {}", file);
10✔
1095
    } catch (IOException e) {
×
1096
      throw new RuntimeException("Failed to write file " + file, e);
×
1097
    }
1✔
1098
  }
1✔
1099

1100
  @Override
1101
  public List<String> readFileLines(Path file) {
1102

1103
    this.context.trace("Reading content of file from {}", file);
10✔
1104
    if (!Files.exists(file)) {
5✔
1105
      this.context.warning("File {} does not exist", file);
10✔
1106
      return null;
2✔
1107
    }
1108
    try {
1109
      List<String> content = Files.readAllLines(file);
3✔
1110
      this.context.trace("Completed reading {} lines from file {}", content.size(), file);
16✔
1111
      return content;
2✔
1112
    } catch (IOException e) {
×
1113
      throw new IllegalStateException("Failed to read file " + file, e);
×
1114
    }
1115
  }
1116

1117
  @Override
1118
  public void writeFileLines(List<String> content, Path file, boolean createParentDir) {
1119

1120
    if (createParentDir) {
2!
1121
      mkdirs(file.getParent());
×
1122
    }
1123
    if (content == null) {
2!
1124
      content = List.of();
×
1125
    }
1126
    this.context.trace("Writing content with {} lines to file {}", content.size(), file);
16✔
1127
    if (Files.exists(file)) {
5✔
1128
      this.context.debug("Overriding content of file {}", file);
10✔
1129
    }
1130
    try {
1131
      Files.write(file, content);
6✔
1132
      this.context.trace("Wrote content to file {}", file);
10✔
1133
    } catch (IOException e) {
×
1134
      throw new RuntimeException("Failed to write file " + file, e);
×
1135
    }
1✔
1136
  }
1✔
1137

1138
  @Override
1139
  public void readProperties(Path file, Properties properties) {
1140

1141
    try (Reader reader = Files.newBufferedReader(file)) {
3✔
1142
      properties.load(reader);
3✔
1143
      this.context.debug("Successfully loaded {} properties from {}", properties.size(), file);
16✔
1144
    } catch (IOException e) {
×
1145
      throw new IllegalStateException("Failed to read properties file: " + file, e);
×
1146
    }
1✔
1147
  }
1✔
1148

1149
  @Override
1150
  public void writeProperties(Properties properties, Path file, boolean createParentDir) {
1151

1152
    if (createParentDir) {
2✔
1153
      mkdirs(file.getParent());
4✔
1154
    }
1155
    try (Writer writer = Files.newBufferedWriter(file)) {
5✔
1156
      properties.store(writer, null); // do not get confused - Java still writes a date/time header that cannot be omitted
4✔
1157
      this.context.debug("Successfully saved {} properties to {}", properties.size(), file);
16✔
1158
    } catch (IOException e) {
×
1159
      throw new IllegalStateException("Failed to save properties file during tests.", e);
×
1160
    }
1✔
1161
  }
1✔
1162

1163
  @Override
1164
  public void readIniFile(Path file, IniFile iniFile) {
1165
    if (!Files.exists(file)) {
5!
1166
      this.context.debug("INI file {} does not exist.", iniFile);
×
1167
      return;
×
1168
    }
1169
    List<String> iniLines = readFileLines(file);
4✔
1170
    IniSection currentIniSection = null;
2✔
1171
    for (String line : iniLines) {
10✔
1172
      if (line.isEmpty()) {
3!
1173
        continue;
×
1174
      }
1175
      if (line.startsWith("[")) {
4✔
1176
        String sectionName = line.replace("[", "").replace("]", "").trim();
9✔
1177
        currentIniSection = iniFile.getOrCreateSection(sectionName);
4✔
1178
      } else {
1✔
1179
        int index = line.indexOf('=');
4✔
1180
        if (index > 0) {
2!
1181
          String propertyName = line.substring(0, index).trim();
6✔
1182
          String propertyValue = line.substring(index + 1).trim();
7✔
1183
          if (currentIniSection == null) {
2!
1184
            Log.warn("Invalid ini-file with property {} before section", propertyName);
×
1185
          } else {
1186
            currentIniSection.getProperties().put(propertyName, propertyValue);
6✔
1187
          }  
1188
        } else {
1189
          // here we can handle comments and empty lines in the future
1190
        }
1191
      }
1192
    }
1✔
1193
  }
1✔
1194

1195
  @Override
1196
  public void writeIniFile(IniFile iniFile, Path file, boolean createParentDir) {
1197
    String iniString = iniFile.toString();
3✔
1198
    writeFileContent(iniString, file, createParentDir);
5✔
1199
  }
1✔
1200

1201
  @Override
1202
  public Duration getFileAge(Path path) {
1203
    if (Files.exists(path)) {
5✔
1204
      try {
1205
        long currentTime = System.currentTimeMillis();
2✔
1206
        long fileModifiedTime = Files.getLastModifiedTime(path).toMillis();
6✔
1207
        return Duration.ofMillis(currentTime - fileModifiedTime);
5✔
1208
      } catch (IOException e) {
×
1209
        this.context.warning().log(e, "Could not get modification-time of {}.", path);
×
1210
      }
×
1211
    } else {
1212
      this.context.debug("Path {} is missing - skipping modification-time and file age check.", path);
10✔
1213
    }
1214
    return null;
2✔
1215
  }
1216

1217
  @Override
1218
  public boolean isFileAgeRecent(Path path, Duration cacheDuration) {
1219

1220
    Duration age = getFileAge(path);
4✔
1221
    if (age == null) {
2✔
1222
      return false;
2✔
1223
    }
1224
    context.debug("The path {} was last updated {} ago and caching duration is {}.", path, age, cacheDuration);
18✔
1225
    return (age.toMillis() <= cacheDuration.toMillis());
10✔
1226
  }
1227
}
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