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

devonfw / IDEasy / 16451580969

22 Jul 2025 05:42PM UTC coverage: 68.388% (-0.06%) from 68.446%
16451580969

Pull #1419

github

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

3290 of 5214 branches covered (63.1%)

Branch coverage included in aggregate %.

8414 of 11900 relevant lines covered (70.71%)

3.12 hits per line

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

66.95
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);
3✔
415
    } else if (SystemInfoImpl.INSTANCE.isWindows() && Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
3!
416
      // On Windows, there might be broken junctions that are not detected by isJunction()
417
      // but still exist and would cause mklink to fail. Try to detect and handle them.
418
      try {
419
        BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
×
420
        if (attrs.isOther()) {
×
421
          // This could be a broken junction or other special file that needs to be removed
422
          this.context.info("Deleting previous special file (possibly broken junction) at " + path);
×
423
          Files.delete(path);
×
424
        }
425
      } catch (IOException e) {
×
426
        // If we can't read attributes, it might be a broken junction
427
        this.context.debug("Could not read attributes of " + path + ", attempting to delete as it may be a broken junction: " + e.getMessage());
×
428
        try {
429
          Files.delete(path);
×
430
          this.context.info("Successfully deleted potentially broken junction at " + path);
×
431
        } catch (IOException deleteEx) {
×
432
          this.context.debug("Failed to delete " + path + ": " + deleteEx.getMessage());
×
433
          // Re-throw the original exception if deletion fails
434
          throw e;
×
435
        }
×
436
      }
×
437
    }
438
  }
1✔
439

440
  /**
441
   * Adapts the given {@link Path} to be relative or absolute depending on the given {@code relative} flag. Additionally, {@link Path#toRealPath(LinkOption...)}
442
   * is applied to {@code source}.
443
   *
444
   * @param source the {@link Path} to adapt.
445
   * @param targetLink the {@link Path} used to calculate the relative path to the {@code source} if {@code relative} is set to {@code true}.
446
   * @param relative the {@code relative} flag.
447
   * @return the adapted {@link Path}.
448
   * @see FileAccessImpl#symlink(Path, Path, boolean)
449
   */
450
  private Path adaptPath(Path source, Path targetLink, boolean relative) throws IOException {
451

452
    if (source.isAbsolute()) {
3✔
453
      try {
454
        source = source.toRealPath(LinkOption.NOFOLLOW_LINKS); // to transform ../d1/../d2 to ../d2
9✔
455
      } catch (IOException e) {
×
456
        throw new IOException("Calling toRealPath() on the source (" + source + ") in method FileAccessImpl.adaptPath() failed.", e);
×
457
      }
1✔
458
      if (relative) {
2✔
459
        source = targetLink.getParent().relativize(source);
5✔
460
        // to make relative links like this work: dir/link -> dir
461
        source = (source.toString().isEmpty()) ? Path.of(".") : source;
12✔
462
      }
463
    } else { // source is relative
464
      if (relative) {
2✔
465
        // even though the source is already relative, toRealPath should be called to transform paths like
466
        // this ../d1/../d2 to ../d2
467
        source = targetLink.getParent().relativize(targetLink.resolveSibling(source).toRealPath(LinkOption.NOFOLLOW_LINKS));
14✔
468
        source = (source.toString().isEmpty()) ? Path.of(".") : source;
12✔
469
      } else { // !relative
470
        try {
471
          source = targetLink.resolveSibling(source).toRealPath(LinkOption.NOFOLLOW_LINKS);
11✔
472
        } catch (IOException e) {
×
473
          throw new IOException("Calling toRealPath() on " + targetLink + ".resolveSibling(" + source + ") in method FileAccessImpl.adaptPath() failed.", e);
×
474
        }
1✔
475
      }
476
    }
477
    return source;
2✔
478
  }
479

480
  /**
481
   * Creates a Windows junction at {@code targetLink} pointing to {@code source}.
482
   *
483
   * @param source must be another Windows junction or a directory.
484
   * @param targetLink the location of the Windows junction.
485
   */
486
  private void createWindowsJunction(Path source, Path targetLink) {
487

488
    this.context.trace("Creating a Windows junction at " + targetLink + " with " + source + " as source.");
×
489
    Path fallbackPath;
490
    if (!source.isAbsolute()) {
×
491
      this.context.warning("You are on Windows and you do not have permissions to create symbolic links. Junctions are used as an "
×
492
          + "alternative, however, these can not point to relative paths. So the source (" + source + ") is interpreted as an absolute path.");
493
      try {
494
        fallbackPath = targetLink.resolveSibling(source).toRealPath(LinkOption.NOFOLLOW_LINKS);
×
495
      } catch (IOException e) {
×
496
        throw new IllegalStateException(
×
497
            "Since Windows junctions are used, the source must be an absolute path. The transformation of the passed " + "source (" + source
498
                + ") to an absolute path failed.", e);
499
      }
×
500

501
    } else {
502
      fallbackPath = source;
×
503
    }
504
    if (!Files.isDirectory(fallbackPath)) { // if source is a junction. This returns true as well.
×
505
      throw new IllegalStateException(
×
506
          "These junctions can only point to directories or other junctions. Please make sure that the source (" + fallbackPath + ") is one of these.");
507
    }
508
    this.context.newProcess().executable("cmd").addArgs("/c", "mklink", "/d", "/j", targetLink.toString(), fallbackPath.toString()).run();
×
509
  }
×
510

511
  @Override
512
  public void symlink(Path source, Path targetLink, boolean relative) {
513

514
    Path adaptedSource = null;
2✔
515
    try {
516
      adaptedSource = adaptPath(source, targetLink, relative);
6✔
517
    } catch (IOException e) {
×
518
      throw new IllegalStateException("Failed to adapt source for source (" + source + ") target (" + targetLink + ") and relative (" + relative + ")", e);
×
519
    }
1✔
520
    this.context.debug("Creating {} symbolic link {} pointing to {}", adaptedSource.isAbsolute() ? "" : "relative", targetLink, adaptedSource);
23✔
521

522
    try {
523
      deleteLinkIfExists(targetLink);
3✔
524
    } catch (IOException e) {
×
525
      throw new IllegalStateException("Failed to delete previous symlink or Windows junction at " + targetLink, e);
×
526
    }
1✔
527

528
    try {
529
      Files.createSymbolicLink(targetLink, adaptedSource);
6✔
530
    } catch (FileSystemException e) {
×
531
      if (SystemInfoImpl.INSTANCE.isWindows()) {
×
532
        this.context.info("Due to lack of permissions, Microsoft's mklink with junction had to be used to create "
×
533
            + "a Symlink. See https://github.com/devonfw/IDEasy/blob/main/documentation/symlink.adoc for " + "further details. Error was: "
534
            + e.getMessage());
×
535
        createWindowsJunction(adaptedSource, targetLink);
×
536
      } else {
537
        throw new RuntimeException(e);
×
538
      }
539
    } catch (IOException e) {
×
540
      throw new IllegalStateException(
×
541
          "Failed to create a " + (adaptedSource.isAbsolute() ? "" : "relative") + "symbolic link " + targetLink + " pointing to " + source, e);
×
542
    }
1✔
543
  }
1✔
544

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

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

551
  @Override
552
  public Path toCanonicalPath(Path path) {
553

554
    return toRealPath(path, false);
5✔
555
  }
556

557
  private Path toRealPath(Path path, boolean resolveLinks) {
558

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

575
  @Override
576
  public Path createTempDir(String name) {
577

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

596
  @Override
597
  public void extract(Path archiveFile, Path targetDir, Consumer<Path> postExtractHook, boolean extract) {
598

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

639
  private void postExtractHook(Consumer<Path> postExtractHook, Path properInstallDir) {
640

641
    if (postExtractHook != null) {
2✔
642
      postExtractHook.accept(properInstallDir);
3✔
643
    }
644
  }
1✔
645

646
  /**
647
   * @param path the {@link Path} to start the recursive search from.
648
   * @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
649
   *     item in their respective directory and {@code s} is not named "bin".
650
   */
651
  private Path getProperInstallationSubDirOf(Path path, Path archiveFile) {
652

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

670
  @Override
671
  public void extractZip(Path file, Path targetDir) {
672

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

690
  @SuppressWarnings("unchecked")
691
  private void onFileCopiedFromZip(Path source, Path target, boolean directory, IdeProgressBar progressBar) {
692

693
    if (directory) {
2✔
694
      return;
1✔
695
    }
696
    if (!context.getSystemInfo().isWindows()) {
5✔
697
      try {
698
        Object attribute = Files.getAttribute(source, "zip:permissions");
6✔
699
        if (attribute instanceof Set<?> permissionSet) {
6✔
700
          Files.setPosixFilePermissions(target, (Set<PosixFilePermission>) permissionSet);
4✔
701
        }
702
      } catch (Exception e) {
×
703
        context.error(e, "Failed to transfer zip permissions for {}", target);
×
704
      }
1✔
705
    }
706
    progressBar.stepBy(getFileSize(target));
5✔
707
  }
1✔
708

709
  @Override
710
  public void extractTar(Path file, Path targetDir, TarCompression compression) {
711

712
    extractArchive(file, targetDir, in -> new TarArchiveInputStream(compression.unpack(in)));
13✔
713
  }
1✔
714

715
  @Override
716
  public void extractJar(Path file, Path targetDir) {
717

718
    extractZip(file, targetDir);
4✔
719
  }
1✔
720

721
  /**
722
   * @param permissions The integer as returned by {@link TarArchiveEntry#getMode()} that represents the file permissions of a file on a Unix file system.
723
   * @return A String representing the file permissions. E.g. "rwxrwxr-x" or "rw-rw-r--"
724
   */
725
  public static String generatePermissionString(int permissions) {
726

727
    // Ensure that only the last 9 bits are considered
728
    permissions &= 0b111111111;
4✔
729

730
    StringBuilder permissionStringBuilder = new StringBuilder("rwxrwxrwx");
5✔
731
    for (int i = 0; i < 9; i++) {
7✔
732
      int mask = 1 << i;
4✔
733
      char currentChar = ((permissions & mask) != 0) ? permissionStringBuilder.charAt(8 - i) : '-';
12✔
734
      permissionStringBuilder.setCharAt(8 - i, currentChar);
6✔
735
    }
736

737
    return permissionStringBuilder.toString();
3✔
738
  }
739

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

742
    this.context.info("Extracting TAR file {} to {}", file, targetDir);
14✔
743
    try (InputStream is = Files.newInputStream(file);
5✔
744
        ArchiveInputStream<?> ais = unpacker.apply(is);
5✔
745
        IdeProgressBar pb = this.context.newProgressbarForExtracting(getFileSize(file))) {
7✔
746

747
      ArchiveEntry entry = ais.getNextEntry();
3✔
748
      boolean isTar = ais instanceof TarArchiveInputStream;
3✔
749
      while (entry != null) {
2✔
750
        String permissionStr = null;
2✔
751
        if (isTar) {
2!
752
          int tarMode = ((TarArchiveEntry) entry).getMode();
4✔
753
          permissionStr = generatePermissionString(tarMode);
3✔
754
        }
755
        Path entryName = Path.of(entry.getName());
6✔
756
        Path entryPath = targetDir.resolve(entryName).toAbsolutePath();
5✔
757
        if (!entryPath.startsWith(targetDir)) {
4!
758
          throw new IOException("Preventing path traversal attack from " + entryName + " to " + entryPath);
×
759
        }
760
        if (entry.isDirectory()) {
3✔
761
          mkdirs(entryPath);
4✔
762
        } else {
763
          // ensure the file can also be created if directory entry was missing or out of order...
764
          mkdirs(entryPath.getParent());
4✔
765
          Files.copy(ais, entryPath);
6✔
766
        }
767
        if (isTar && !this.context.getSystemInfo().isWindows()) {
7!
768
          Set<PosixFilePermission> permissions = PosixFilePermissions.fromString(permissionStr);
3✔
769
          Files.setPosixFilePermissions(entryPath, permissions);
4✔
770
        }
771
        pb.stepBy(entry.getSize());
4✔
772
        entry = ais.getNextEntry();
3✔
773
      }
1✔
774
    } catch (IOException e) {
×
775
      throw new IllegalStateException("Failed to extract " + file + " to " + targetDir, e);
×
776
    }
1✔
777
  }
1✔
778

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

782
    this.context.info("Extracting DMG file {} to {}", file, targetDir);
×
783
    assert this.context.getSystemInfo().isMac();
×
784

785
    Path mountPath = this.context.getIdeHome().resolve(IdeContext.FOLDER_UPDATES).resolve(IdeContext.FOLDER_VOLUME);
×
786
    mkdirs(mountPath);
×
787
    ProcessContext pc = this.context.newProcess();
×
788
    pc.executable("hdiutil");
×
789
    pc.addArgs("attach", "-quiet", "-nobrowse", "-mountpoint", mountPath, file);
×
790
    pc.run();
×
791
    Path appPath = findFirst(mountPath, p -> p.getFileName().toString().endsWith(".app"), false);
×
792
    if (appPath == null) {
×
793
      throw new IllegalStateException("Failed to unpack DMG as no MacOS *.app was found in file " + file);
×
794
    }
795

796
    copy(appPath, targetDir, FileCopyMode.COPY_TREE_OVERRIDE_TREE);
×
797
    pc.addArgs("detach", "-force", mountPath);
×
798
    pc.run();
×
799
  }
×
800

801
  @Override
802
  public void extractMsi(Path file, Path targetDir) {
803

804
    this.context.info("Extracting MSI file {} to {}", file, targetDir);
×
805
    this.context.newProcess().executable("msiexec").addArgs("/a", file, "/qn", "TARGETDIR=" + targetDir).run();
×
806
    // msiexec also creates a copy of the MSI
807
    Path msiCopy = targetDir.resolve(file.getFileName());
×
808
    delete(msiCopy);
×
809
  }
×
810

811
  @Override
812
  public void extractPkg(Path file, Path targetDir) {
813

814
    this.context.info("Extracting PKG file {} to {}", file, targetDir);
×
815
    Path tmpDirPkg = createTempDir("ide-pkg-");
×
816
    ProcessContext pc = this.context.newProcess();
×
817
    // we might also be able to use cpio from commons-compression instead of external xar...
818
    pc.executable("xar").addArgs("-C", tmpDirPkg, "-xf", file).run();
×
819
    Path contentPath = findFirst(tmpDirPkg, p -> p.getFileName().toString().equals("Payload"), true);
×
820
    extractTar(contentPath, targetDir, TarCompression.GZ);
×
821
    delete(tmpDirPkg);
×
822
  }
×
823

824
  @Override
825
  public void delete(Path path) {
826

827
    if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
9✔
828
      this.context.trace("Deleting {} skipped as the path does not exist.", path);
10✔
829
      return;
1✔
830
    }
831
    this.context.debug("Deleting {} ...", path);
10✔
832
    try {
833
      if (Files.isSymbolicLink(path) || isJunction(path)) {
7!
834
        Files.delete(path);
3✔
835
      } else {
836
        deleteRecursive(path);
3✔
837
      }
838
    } catch (IOException e) {
×
839
      throw new IllegalStateException("Failed to delete " + path, e);
×
840
    }
1✔
841
  }
1✔
842

843
  private void deleteRecursive(Path path) throws IOException {
844

845
    if (Files.isDirectory(path)) {
5✔
846
      try (Stream<Path> childStream = Files.list(path)) {
3✔
847
        Iterator<Path> iterator = childStream.iterator();
3✔
848
        while (iterator.hasNext()) {
3✔
849
          Path child = iterator.next();
4✔
850
          deleteRecursive(child);
3✔
851
        }
1✔
852
      }
853
    }
854
    this.context.trace("Deleting {} ...", path);
10✔
855
    boolean isSetWritable = setWritable(path, true);
5✔
856
    if (!isSetWritable) {
2✔
857
      this.context.debug("Couldn't give write access to file: " + path);
6✔
858
    }
859
    Files.delete(path);
2✔
860
  }
1✔
861

862
  @Override
863
  public Path findFirst(Path dir, Predicate<Path> filter, boolean recursive) {
864

865
    try {
866
      if (!Files.isDirectory(dir)) {
5✔
867
        return null;
2✔
868
      }
869
      return findFirstRecursive(dir, filter, recursive);
6✔
870
    } catch (IOException e) {
×
871
      throw new IllegalStateException("Failed to search for file in " + dir, e);
×
872
    }
873
  }
874

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

877
    List<Path> folders = null;
2✔
878
    try (Stream<Path> childStream = Files.list(dir)) {
3✔
879
      Iterator<Path> iterator = childStream.iterator();
3✔
880
      while (iterator.hasNext()) {
3✔
881
        Path child = iterator.next();
4✔
882
        if (filter.test(child)) {
4✔
883
          return child;
4✔
884
        } else if (recursive && Files.isDirectory(child)) {
2!
885
          if (folders == null) {
×
886
            folders = new ArrayList<>();
×
887
          }
888
          folders.add(child);
×
889
        }
890
      }
1✔
891
    }
4!
892
    if (folders != null) {
2!
893
      for (Path child : folders) {
×
894
        Path match = findFirstRecursive(child, filter, recursive);
×
895
        if (match != null) {
×
896
          return match;
×
897
        }
898
      }
×
899
    }
900
    return null;
2✔
901
  }
902

903
  @Override
904
  public List<Path> listChildrenMapped(Path dir, Function<Path, Path> filter) {
905

906
    if (!Files.isDirectory(dir)) {
5✔
907
      return List.of();
2✔
908
    }
909
    List<Path> children = new ArrayList<>();
4✔
910
    try (Stream<Path> childStream = Files.list(dir)) {
3✔
911
      Iterator<Path> iterator = childStream.iterator();
3✔
912
      while (iterator.hasNext()) {
3✔
913
        Path child = iterator.next();
4✔
914
        Path filteredChild = filter.apply(child);
5✔
915
        if (filteredChild != null) {
2✔
916
          if (filteredChild == child) {
3!
917
            this.context.trace("Accepted file {}", child);
11✔
918
          } else {
919
            this.context.trace("Accepted file {} and mapped to {}", child, filteredChild);
×
920
          }
921
          children.add(filteredChild);
5✔
922
        } else {
923
          this.context.trace("Ignoring file {} according to filter", child);
10✔
924
        }
925
      }
1✔
926
    } catch (IOException e) {
×
927
      throw new IllegalStateException("Failed to find children of directory " + dir, e);
×
928
    }
1✔
929
    return children;
2✔
930
  }
931

932
  @Override
933
  public boolean isEmptyDir(Path dir) {
934

935
    return listChildren(dir, f -> true).isEmpty();
8✔
936
  }
937

938
  private long getFileSize(Path file) {
939

940
    try {
941
      return Files.size(file);
3✔
942
    } catch (IOException e) {
×
943
      this.context.warning(e.getMessage(), e);
×
944
      return 0;
×
945
    }
946
  }
947

948
  private long getFileSizeRecursive(Path path) {
949

950
    long size = 0;
2✔
951
    if (Files.isDirectory(path)) {
5✔
952
      try (Stream<Path> childStream = Files.list(path)) {
3✔
953
        Iterator<Path> iterator = childStream.iterator();
3✔
954
        while (iterator.hasNext()) {
3✔
955
          Path child = iterator.next();
4✔
956
          size += getFileSizeRecursive(child);
6✔
957
        }
1✔
958
      } catch (IOException e) {
×
959
        throw new RuntimeException("Failed to iterate children of folder " + path, e);
×
960
      }
1✔
961
    } else {
962
      size += getFileSize(path);
6✔
963
    }
964
    return size;
2✔
965
  }
966

967
  @Override
968
  public Path findExistingFile(String fileName, List<Path> searchDirs) {
969

970
    for (Path dir : searchDirs) {
10!
971
      Path filePath = dir.resolve(fileName);
4✔
972
      try {
973
        if (Files.exists(filePath)) {
5✔
974
          return filePath;
2✔
975
        }
976
      } catch (Exception e) {
×
977
        throw new IllegalStateException("Unexpected error while checking existence of file " + filePath + " .", e);
×
978
      }
1✔
979
    }
1✔
980
    return null;
×
981
  }
982

983
  @Override
984
  public boolean setWritable(Path file, boolean writable) {
985
    try {
986
      // POSIX
987
      PosixFileAttributeView posix = Files.getFileAttributeView(file, PosixFileAttributeView.class);
7✔
988
      if (posix != null) {
2!
989
        Set<PosixFilePermission> permissions = new HashSet<>(posix.readAttributes().permissions());
7✔
990
        boolean changed;
991
        if (writable) {
2!
992
          changed = permissions.add(PosixFilePermission.OWNER_WRITE);
5✔
993
        } else {
994
          changed = permissions.remove(PosixFilePermission.OWNER_WRITE);
×
995
        }
996
        if (changed) {
2!
997
          posix.setPermissions(permissions);
×
998
        }
999
        return true;
2✔
1000
      }
1001

1002
      // Windows
1003
      DosFileAttributeView dos = Files.getFileAttributeView(file, DosFileAttributeView.class);
×
1004
      if (dos != null) {
×
1005
        dos.setReadOnly(!writable);
×
1006
        return true;
×
1007
      }
1008

1009
      this.context.debug("Failed to set writing permission for file {}", file);
×
1010
      return false;
×
1011

1012
    } catch (IOException e) {
1✔
1013
      this.context.debug("Error occurred when trying to set writing permission for file " + file + ": " + e);
8✔
1014
      return false;
2✔
1015
    }
1016
  }
1017

1018
  @Override
1019
  public void makeExecutable(Path file, boolean confirm) {
1020

1021
    if (Files.exists(file)) {
5✔
1022
      if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
1023
        this.context.trace("Windows does not have executable flags hence omitting for file {}", file);
×
1024
        return;
×
1025
      }
1026
      try {
1027
        // Read the current file permissions
1028
        Set<PosixFilePermission> existingPermissions = Files.getPosixFilePermissions(file);
5✔
1029

1030
        // Add execute permission for all users
1031
        Set<PosixFilePermission> executablePermissions = new HashSet<>(existingPermissions);
5✔
1032
        boolean update = false;
2✔
1033
        update |= executablePermissions.add(PosixFilePermission.OWNER_EXECUTE);
6✔
1034
        update |= executablePermissions.add(PosixFilePermission.GROUP_EXECUTE);
6✔
1035
        update |= executablePermissions.add(PosixFilePermission.OTHERS_EXECUTE);
6✔
1036

1037
        if (update) {
2✔
1038
          if (confirm) {
2!
1039
            boolean yesContinue = this.context.question(
×
1040
                "We want to execute " + file.getFileName() + " but this command seems to lack executable permissions!\n"
×
1041
                    + "Most probably the tool vendor did forgot to add x-flags in the binary release package.\n"
1042
                    + "Before running the command, we suggest to set executable permissions to the file:\n"
1043
                    + file + "\n"
1044
                    + "For security reasons we ask for your confirmation so please check this request.\n"
1045
                    + "Changing permissions from " + PosixFilePermissions.toString(existingPermissions) + " to " + PosixFilePermissions.toString(
×
1046
                    executablePermissions) + ".\n"
1047
                    + "Do you confirm to make the command executable before running it?");
1048
            if (!yesContinue) {
×
1049
              return;
×
1050
            }
1051
          }
1052
          this.context.debug("Setting executable flags for file {}", file);
10✔
1053
          // Set the new permissions
1054
          Files.setPosixFilePermissions(file, executablePermissions);
5✔
1055
        } else {
1056
          this.context.trace("Executable flags already present so no need to set them for file {}", file);
10✔
1057
        }
1058
      } catch (IOException e) {
×
1059
        throw new RuntimeException(e);
×
1060
      }
1✔
1061
    } else {
1062
      this.context.warning("Cannot set executable flag on file that does not exist: {}", file);
10✔
1063
    }
1064
  }
1✔
1065

1066
  @Override
1067
  public void touch(Path file) {
1068

1069
    if (Files.exists(file)) {
5✔
1070
      try {
1071
        Files.setLastModifiedTime(file, FileTime.fromMillis(System.currentTimeMillis()));
5✔
1072
      } catch (IOException e) {
×
1073
        throw new IllegalStateException("Could not update modification-time of " + file, e);
×
1074
      }
1✔
1075
    } else {
1076
      try {
1077
        Files.createFile(file);
5✔
1078
      } catch (IOException e) {
1✔
1079
        throw new IllegalStateException("Could not create empty file " + file, e);
8✔
1080
      }
1✔
1081
    }
1082
  }
1✔
1083

1084
  @Override
1085
  public String readFileContent(Path file) {
1086

1087
    this.context.trace("Reading content of file from {}", file);
10✔
1088
    if (!Files.exists((file))) {
5!
1089
      this.context.debug("File {} does not exist", file);
×
1090
      return null;
×
1091
    }
1092
    try {
1093
      String content = Files.readString(file);
3✔
1094
      this.context.trace("Completed reading {} character(s) from file {}", content.length(), file);
16✔
1095
      return content;
2✔
1096
    } catch (IOException e) {
×
1097
      throw new IllegalStateException("Failed to read file " + file, e);
×
1098
    }
1099
  }
1100

1101
  @Override
1102
  public void writeFileContent(String content, Path file, boolean createParentDir) {
1103

1104
    if (createParentDir) {
2✔
1105
      mkdirs(file.getParent());
4✔
1106
    }
1107
    if (content == null) {
2!
1108
      content = "";
×
1109
    }
1110
    this.context.trace("Writing content with {} character(s) to file {}", content.length(), file);
16✔
1111
    if (Files.exists(file)) {
5✔
1112
      this.context.info("Overriding content of file {}", file);
10✔
1113
    }
1114
    try {
1115
      Files.writeString(file, content);
6✔
1116
      this.context.trace("Wrote content to file {}", file);
10✔
1117
    } catch (IOException e) {
×
1118
      throw new RuntimeException("Failed to write file " + file, e);
×
1119
    }
1✔
1120
  }
1✔
1121

1122
  @Override
1123
  public List<String> readFileLines(Path file) {
1124

1125
    this.context.trace("Reading content of file from {}", file);
10✔
1126
    if (!Files.exists(file)) {
5✔
1127
      this.context.warning("File {} does not exist", file);
10✔
1128
      return null;
2✔
1129
    }
1130
    try {
1131
      List<String> content = Files.readAllLines(file);
3✔
1132
      this.context.trace("Completed reading {} lines from file {}", content.size(), file);
16✔
1133
      return content;
2✔
1134
    } catch (IOException e) {
×
1135
      throw new IllegalStateException("Failed to read file " + file, e);
×
1136
    }
1137
  }
1138

1139
  @Override
1140
  public void writeFileLines(List<String> content, Path file, boolean createParentDir) {
1141

1142
    if (createParentDir) {
2!
1143
      mkdirs(file.getParent());
×
1144
    }
1145
    if (content == null) {
2!
1146
      content = List.of();
×
1147
    }
1148
    this.context.trace("Writing content with {} lines to file {}", content.size(), file);
16✔
1149
    if (Files.exists(file)) {
5✔
1150
      this.context.debug("Overriding content of file {}", file);
10✔
1151
    }
1152
    try {
1153
      Files.write(file, content);
6✔
1154
      this.context.trace("Wrote content to file {}", file);
10✔
1155
    } catch (IOException e) {
×
1156
      throw new RuntimeException("Failed to write file " + file, e);
×
1157
    }
1✔
1158
  }
1✔
1159

1160
  @Override
1161
  public void readProperties(Path file, Properties properties) {
1162

1163
    try (Reader reader = Files.newBufferedReader(file)) {
3✔
1164
      properties.load(reader);
3✔
1165
      this.context.debug("Successfully loaded {} properties from {}", properties.size(), file);
16✔
1166
    } catch (IOException e) {
×
1167
      throw new IllegalStateException("Failed to read properties file: " + file, e);
×
1168
    }
1✔
1169
  }
1✔
1170

1171
  @Override
1172
  public void writeProperties(Properties properties, Path file, boolean createParentDir) {
1173

1174
    if (createParentDir) {
2✔
1175
      mkdirs(file.getParent());
4✔
1176
    }
1177
    try (Writer writer = Files.newBufferedWriter(file)) {
5✔
1178
      properties.store(writer, null); // do not get confused - Java still writes a date/time header that cannot be omitted
4✔
1179
      this.context.debug("Successfully saved {} properties to {}", properties.size(), file);
16✔
1180
    } catch (IOException e) {
×
1181
      throw new IllegalStateException("Failed to save properties file during tests.", e);
×
1182
    }
1✔
1183
  }
1✔
1184

1185
  @Override
1186
  public void readIniFile(Path file, IniFile iniFile) {
1187
    if (!Files.exists(file)) {
5!
1188
      this.context.debug("INI file {} does not exist.", iniFile);
×
1189
      return;
×
1190
    }
1191
    List<String> iniLines = readFileLines(file);
4✔
1192
    IniSection currentIniSection = null;
2✔
1193
    for (String line : iniLines) {
10✔
1194
      if (line.isEmpty()) {
3!
1195
        continue;
×
1196
      }
1197
      if (line.startsWith("[")) {
4✔
1198
        String sectionName = line.replace("[", "").replace("]", "").trim();
9✔
1199
        currentIniSection = iniFile.getOrCreateSection(sectionName);
4✔
1200
      } else {
1✔
1201
        int index = line.indexOf('=');
4✔
1202
        if (index > 0) {
2!
1203
          String propertyName = line.substring(0, index).trim();
6✔
1204
          String propertyValue = line.substring(index + 1).trim();
7✔
1205
          if (currentIniSection == null) {
2!
1206
            Log.warn("Invalid ini-file with property {} before section", propertyName);
×
1207
          } else {
1208
            currentIniSection.getProperties().put(propertyName, propertyValue);
6✔
1209
          }  
1210
        } else {
1211
          // here we can handle comments and empty lines in the future
1212
        }
1213
      }
1214
    }
1✔
1215
  }
1✔
1216

1217
  @Override
1218
  public void writeIniFile(IniFile iniFile, Path file, boolean createParentDir) {
1219
    String iniString = iniFile.toString();
3✔
1220
    writeFileContent(iniString, file, createParentDir);
5✔
1221
  }
1✔
1222

1223
  @Override
1224
  public Duration getFileAge(Path path) {
1225
    if (Files.exists(path)) {
5✔
1226
      try {
1227
        long currentTime = System.currentTimeMillis();
2✔
1228
        long fileModifiedTime = Files.getLastModifiedTime(path).toMillis();
6✔
1229
        return Duration.ofMillis(currentTime - fileModifiedTime);
5✔
1230
      } catch (IOException e) {
×
1231
        this.context.warning().log(e, "Could not get modification-time of {}.", path);
×
1232
      }
×
1233
    } else {
1234
      this.context.debug("Path {} is missing - skipping modification-time and file age check.", path);
10✔
1235
    }
1236
    return null;
2✔
1237
  }
1238

1239
  @Override
1240
  public boolean isFileAgeRecent(Path path, Duration cacheDuration) {
1241

1242
    Duration age = getFileAge(path);
4✔
1243
    if (age == null) {
2✔
1244
      return false;
2✔
1245
    }
1246
    context.debug("The path {} was last updated {} ago and caching duration is {}.", path, age, cacheDuration);
18✔
1247
    return (age.toMillis() <= cacheDuration.toMillis());
10✔
1248
  }
1249
}
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