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

devonfw / IDEasy / 16903197016

12 Aug 2025 08:20AM UTC coverage: 69.308% (-0.07%) from 69.373%
16903197016

Pull #1442

github

web-flow
Merge 7dedfc535 into 8e46cb00a
Pull Request #1442: #1384: Add python support via uv

3356 of 5278 branches covered (63.58%)

Branch coverage included in aggregate %.

8671 of 12075 relevant lines covered (71.81%)

3.16 hits per line

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

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

49
import org.apache.commons.compress.archivers.ArchiveEntry;
50
import org.apache.commons.compress.archivers.ArchiveInputStream;
51
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
52
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
53

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

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

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

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

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

80
  private final IdeContext context;
81

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

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

93
  private HttpClient createHttpClient(String url) {
94

95
    HttpClient.Builder builder = HttpClient.newBuilder().followRedirects(Redirect.ALWAYS);
4✔
96
    return builder.build();
3✔
97
  }
98

99
  @Override
100
  public void download(String url, Path target) {
101
    List<Version> httpProtocols = IdeVariables.HTTP_VERSIONS.get(context);
6✔
102

103
    Exception lastException = null;
2✔
104
    if (httpProtocols.isEmpty()) {
3!
105
      try {
106
        this.downloadWithHttpVersion(url, target, null);
5✔
107
        return; // success
1✔
108
      } catch (Exception e) {
×
109
        lastException = e;
×
110
      }
×
111
    } else {
112
      for (Version version : httpProtocols) {
×
113
        try {
114
          this.context.debug("Trying to download: {} with HTTP protocol version: {}", url, version);
×
115
          this.downloadWithHttpVersion(url, target, version);
×
116
          return; // success
×
117
        } catch (Exception ex) {
×
118
          lastException = ex;
×
119
        }
120
      }
×
121
    }
122

123
    throw new IllegalStateException("Failed to download file from URL " + url + " to " + target, lastException);
×
124
  }
125

126
  private void downloadWithHttpVersion(String url, Path target, Version httpVersion) throws Exception {
127

128
    this.context.info("Trying to download {} from {}", target.getFileName(), url);
15✔
129
    mkdirs(target.getParent());
4✔
130

131
    if (this.context.isOffline()) {
4!
132
      throw CliOfflineException.ofDownloadViaUrl(url);
×
133
    }
134
    if (url.startsWith("http")) {
4✔
135

136
      Builder builder = HttpRequest.newBuilder()
2✔
137
          .uri(URI.create(url))
2✔
138
          .GET();
2✔
139
      if (httpVersion != null) {
2!
140
        builder.version(httpVersion);
×
141
      }
142
      HttpRequest request = builder.build();
3✔
143
      HttpResponse<InputStream> response;
144
      HttpClient client = createHttpClient(url);
4✔
145
      response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
5✔
146
      int statusCode = response.statusCode();
3✔
147
      if (statusCode == 200) {
3!
148
        downloadFileWithProgressBar(url, target, response);
6✔
149
      } else {
150
        throw new IllegalStateException("Download failed with status code " + statusCode);
×
151
      }
152
    } else if (url.startsWith("ftp") || url.startsWith("sftp")) {
9!
153
      throw new IllegalArgumentException("Unsupported download URL: " + url);
×
154
    } else {
155
      Path source = Path.of(url);
5✔
156
      if (isFile(source)) {
4!
157
        // network drive
158

159
        copyFileWithProgressBar(source, target);
5✔
160
      } else {
161
        throw new IllegalArgumentException("Download path does not point to a downloadable file: " + url);
×
162
      }
163
    }
164
  }
1✔
165

166
  /**
167
   * Downloads a file while showing a {@link IdeProgressBar}.
168
   *
169
   * @param url the url to download.
170
   * @param target Path of the target directory.
171
   * @param response the {@link HttpResponse} to use.
172
   */
173
  private void downloadFileWithProgressBar(String url, Path target, HttpResponse<InputStream> response) {
174

175
    long contentLength = response.headers().firstValueAsLong("content-length").orElse(-1);
7✔
176
    informAboutMissingContentLength(contentLength, url);
4✔
177

178
    byte[] data = new byte[1024];
3✔
179
    boolean fileComplete = false;
2✔
180
    int count;
181

182
    try (InputStream body = response.body();
4✔
183
        FileOutputStream fileOutput = new FileOutputStream(target.toFile());
6✔
184
        BufferedOutputStream bufferedOut = new BufferedOutputStream(fileOutput, data.length);
7✔
185
        IdeProgressBar pb = this.context.newProgressBarForDownload(contentLength)) {
5✔
186
      while (!fileComplete) {
2✔
187
        count = body.read(data);
4✔
188
        if (count <= 0) {
2✔
189
          fileComplete = true;
3✔
190
        } else {
191
          bufferedOut.write(data, 0, count);
5✔
192
          pb.stepBy(count);
5✔
193
        }
194
      }
195

196
    } catch (Exception e) {
×
197
      throw new RuntimeException(e);
×
198
    }
1✔
199
  }
1✔
200

201
  /**
202
   * Copies a file while displaying a progress bar.
203
   *
204
   * @param source Path of file to copy.
205
   * @param target Path of target directory.
206
   */
207
  private void copyFileWithProgressBar(Path source, Path target) throws IOException {
208

209
    try (InputStream in = new FileInputStream(source.toFile()); OutputStream out = new FileOutputStream(target.toFile())) {
12✔
210
      long size = getFileSize(source);
4✔
211
      byte[] buf = new byte[1024];
3✔
212
      try (IdeProgressBar pb = this.context.newProgressbarForCopying(size)) {
5✔
213
        int readBytes;
214
        while ((readBytes = in.read(buf)) > 0) {
6✔
215
          out.write(buf, 0, readBytes);
5✔
216
          if (size > 0) {
4!
217
            pb.stepBy(readBytes);
5✔
218
          }
219
        }
220
      } catch (Exception e) {
×
221
        throw new RuntimeException(e);
×
222
      }
1✔
223
    }
224
  }
1✔
225

226
  private void informAboutMissingContentLength(long contentLength, String url) {
227

228
    if (contentLength < 0) {
4✔
229
      this.context.warning("Content-Length was not provided by download from {}", url);
10✔
230
    }
231
  }
1✔
232

233
  @Override
234
  public void mkdirs(Path directory) {
235

236
    if (Files.isDirectory(directory)) {
5✔
237
      return;
1✔
238
    }
239
    this.context.trace("Creating directory {}", directory);
10✔
240
    try {
241
      Files.createDirectories(directory);
5✔
242
    } catch (IOException e) {
×
243
      throw new IllegalStateException("Failed to create directory " + directory, e);
×
244
    }
1✔
245
  }
1✔
246

247
  @Override
248
  public boolean isFile(Path file) {
249

250
    if (!Files.exists(file)) {
5!
251
      this.context.trace("File {} does not exist", file);
×
252
      return false;
×
253
    }
254
    if (Files.isDirectory(file)) {
5!
255
      this.context.trace("Path {} is a directory but a regular file was expected", file);
×
256
      return false;
×
257
    }
258
    return true;
2✔
259
  }
260

261
  @Override
262
  public boolean isExpectedFolder(Path folder) {
263

264
    if (Files.isDirectory(folder)) {
5✔
265
      return true;
2✔
266
    }
267
    this.context.warning("Expected folder was not found at {}", folder);
10✔
268
    return false;
2✔
269
  }
270

271
  @Override
272
  public String checksum(Path file, String hashAlgorithm) {
273

274
    MessageDigest md;
275
    try {
276
      md = MessageDigest.getInstance(hashAlgorithm);
×
277
    } catch (NoSuchAlgorithmException e) {
×
278
      throw new IllegalStateException("No such hash algorithm " + hashAlgorithm, e);
×
279
    }
×
280
    byte[] buffer = new byte[1024];
×
281
    try (InputStream is = Files.newInputStream(file); DigestInputStream dis = new DigestInputStream(is, md)) {
×
282
      int read = 0;
×
283
      while (read >= 0) {
×
284
        read = dis.read(buffer);
×
285
      }
286
    } catch (Exception e) {
×
287
      throw new IllegalStateException("Failed to read and hash file " + file, e);
×
288
    }
×
289
    byte[] digestBytes = md.digest();
×
290
    return HexUtil.toHexString(digestBytes);
×
291
  }
292

293
  public boolean isJunction(Path path) {
294

295
    if (!SystemInfoImpl.INSTANCE.isWindows()) {
3!
296
      return false;
2✔
297
    }
298

299
    try {
300
      BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
×
301
      return attr.isOther() && attr.isDirectory();
×
302
    } catch (NoSuchFileException e) {
×
303
      return false; // file doesn't exist
×
304
    } catch (IOException e) {
×
305
      // errors in reading the attributes of the file
306
      throw new IllegalStateException("An unexpected error occurred whilst checking if the file: " + path + " is a junction", e);
×
307
    }
308
  }
309

310
  @Override
311
  public Path backup(Path fileOrFolder) {
312

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

333
  private static Path appendParentPath(Path path, Path parent, int max) {
334

335
    if ((parent == null) || (max <= 0)) {
4!
336
      return path;
2✔
337
    }
338
    return appendParentPath(path, parent.getParent(), max - 1).resolve(parent.getFileName());
11✔
339
  }
340

341
  @Override
342
  public void move(Path source, Path targetDir, StandardCopyOption... copyOptions) {
343

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

357
  @Override
358
  public void copy(Path source, Path target, FileCopyMode mode, PathCopyListener listener) {
359

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

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

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

426
  /**
427
   * 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
428
   * {@link Path} that is neither a symbolic link nor a Windows junction.
429
   *
430
   * @param path the {@link Path} to delete.
431
   * @throws IOException if the actual {@link Files#delete(Path) deletion} fails.
432
   */
433
  private void deleteLinkIfExists(Path path) throws IOException {
434

435
    boolean isJunction = isJunction(path); // since broken junctions are not detected by Files.exists()
4✔
436
    boolean isSymlink = Files.exists(path) && Files.isSymbolicLink(path);
12!
437

438
    assert !(isSymlink && isJunction);
5!
439

440
    if (isJunction || isSymlink) {
4!
441
      this.context.info("Deleting previous " + (isJunction ? "junction" : "symlink") + " at " + path);
9!
442
      Files.delete(path);
2✔
443
    }
444
  }
1✔
445

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

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

486
  /**
487
   * Creates a Windows junction at {@code targetLink} pointing to {@code source}.
488
   *
489
   * @param source must be another Windows junction or a directory.
490
   * @param targetLink the location of the Windows junction.
491
   */
492
  private void createWindowsJunction(Path source, Path targetLink) {
493

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

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

517
  @Override
518
  public void symlink(Path source, Path targetLink, boolean relative) {
519

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

528
    try {
529
      deleteLinkIfExists(targetLink);
3✔
530
    } catch (IOException e) {
×
531
      throw new IllegalStateException("Failed to delete previous symlink or Windows junction at " + targetLink, e);
×
532
    }
1✔
533

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

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

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

557
  @Override
558
  public Path toCanonicalPath(Path path) {
559

560
    return toRealPath(path, false);
5✔
561
  }
562

563
  private Path toRealPath(Path path, boolean resolveLinks) {
564

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

581
  @Override
582
  public Path createTempDir(String name) {
583

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

602
  @Override
603
  public void extract(Path archiveFile, Path targetDir, Consumer<Path> postExtractHook, boolean extract) {
604

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

645
  private void postExtractHook(Consumer<Path> postExtractHook, Path properInstallDir) {
646

647
    if (postExtractHook != null) {
2✔
648
      postExtractHook.accept(properInstallDir);
3✔
649
    }
650
  }
1✔
651

652
  /**
653
   * @param path the {@link Path} to start the recursive search from.
654
   * @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
655
   *     item in their respective directory and {@code s} is not named "bin".
656
   */
657
  private Path getProperInstallationSubDirOf(Path path, Path archiveFile) {
658

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

676
  @Override
677
  public void extractZip(Path file, Path targetDir) {
678

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

696
  @SuppressWarnings("unchecked")
697
  private void onFileCopiedFromZip(Path source, Path target, boolean directory, IdeProgressBar progressBar) {
698

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

715
  @Override
716
  public void extractTar(Path file, Path targetDir, TarCompression compression) {
717

718
    extractArchive(file, targetDir, in -> new TarArchiveInputStream(compression.unpack(in)));
13✔
719
  }
1✔
720

721
  @Override
722
  public void extractJar(Path file, Path targetDir) {
723

724
    extractZip(file, targetDir);
4✔
725
  }
1✔
726

727
  /**
728
   * @param permissions The integer as returned by {@link TarArchiveEntry#getMode()} that represents the file permissions of a file on a Unix file system.
729
   * @return A String representing the file permissions. E.g. "rwxrwxr-x" or "rw-rw-r--"
730
   */
731
  public static String generatePermissionString(int permissions) {
732

733
    // Ensure that only the last 9 bits are considered
734
    permissions &= 0b111111111;
4✔
735

736
    StringBuilder permissionStringBuilder = new StringBuilder("rwxrwxrwx");
5✔
737
    for (int i = 0; i < 9; i++) {
7✔
738
      int mask = 1 << i;
4✔
739
      char currentChar = ((permissions & mask) != 0) ? permissionStringBuilder.charAt(8 - i) : '-';
12✔
740
      permissionStringBuilder.setCharAt(8 - i, currentChar);
6✔
741
    }
742

743
    return permissionStringBuilder.toString();
3✔
744
  }
745

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

748
    this.context.info("Extracting TAR file {} to {}", file, targetDir);
14✔
749
    try (InputStream is = Files.newInputStream(file);
5✔
750
        ArchiveInputStream<?> ais = unpacker.apply(is);
5✔
751
        IdeProgressBar pb = this.context.newProgressbarForExtracting(getFileSize(file))) {
7✔
752

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

785
  @Override
786
  public void extractDmg(Path file, Path targetDir) {
787

788
    this.context.info("Extracting DMG file {} to {}", file, targetDir);
×
789
    assert this.context.getSystemInfo().isMac();
×
790

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

802
    copy(appPath, targetDir, FileCopyMode.COPY_TREE_OVERRIDE_TREE);
×
803
    pc.addArgs("detach", "-force", mountPath);
×
804
    pc.run();
×
805
  }
×
806

807
  @Override
808
  public void extractMsi(Path file, Path targetDir) {
809

810
    this.context.info("Extracting MSI file {} to {}", file, targetDir);
×
811
    this.context.newProcess().executable("msiexec").addArgs("/a", file, "/qn", "TARGETDIR=" + targetDir).run();
×
812
    // msiexec also creates a copy of the MSI
813
    Path msiCopy = targetDir.resolve(file.getFileName());
×
814
    delete(msiCopy);
×
815
  }
×
816

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

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

830
  @Override
831
  public void delete(Path path) {
832

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

849
  private void deleteRecursive(Path path) throws IOException {
850

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

868
  @Override
869
  public Path findFirst(Path dir, Predicate<Path> filter, boolean recursive) {
870

871
    try {
872
      if (!Files.isDirectory(dir)) {
5✔
873
        return null;
2✔
874
      }
875
      return findFirstRecursive(dir, filter, recursive);
6✔
876
    } catch (IOException e) {
×
877
      throw new IllegalStateException("Failed to search for file in " + dir, e);
×
878
    }
879
  }
880

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

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

909
  @Override
910
  public List<Path> listChildrenMapped(Path dir, Function<Path, Path> filter) {
911

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

938
  @Override
939
  public boolean isEmptyDir(Path dir) {
940

941
    return listChildren(dir, f -> true).isEmpty();
8✔
942
  }
943

944
  private long getFileSize(Path file) {
945

946
    try {
947
      return Files.size(file);
3✔
948
    } catch (IOException e) {
×
949
      this.context.warning(e.getMessage(), e);
×
950
      return 0;
×
951
    }
952
  }
953

954
  private long getFileSizeRecursive(Path path) {
955

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

973
  @Override
974
  public Path findExistingFile(String fileName, List<Path> searchDirs) {
975

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

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

1008
      // Windows
1009
      DosFileAttributeView dos = Files.getFileAttributeView(file, DosFileAttributeView.class);
×
1010
      if (dos != null) {
×
1011
        dos.setReadOnly(!writable);
×
1012
        return true;
×
1013
      }
1014

1015
      this.context.debug("Failed to set writing permission for file {}", file);
×
1016
      return false;
×
1017

1018
    } catch (IOException e) {
1✔
1019
      this.context.debug("Error occurred when trying to set writing permission for file " + file + ": " + e);
8✔
1020
      return false;
2✔
1021
    }
1022
  }
1023

1024
  @Override
1025
  public void makeExecutable(Path file, boolean confirm) {
1026

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

1036
        // Add execute permission for all users
1037
        Set<PosixFilePermission> executablePermissions = new HashSet<>(existingPermissions);
5✔
1038
        boolean update = false;
2✔
1039
        update |= executablePermissions.add(PosixFilePermission.OWNER_EXECUTE);
6✔
1040
        update |= executablePermissions.add(PosixFilePermission.GROUP_EXECUTE);
6✔
1041
        update |= executablePermissions.add(PosixFilePermission.OTHERS_EXECUTE);
6✔
1042

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

1072
  @Override
1073
  public void touch(Path file) {
1074

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

1090
  @Override
1091
  public String readFileContent(Path file) {
1092

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

1107
  @Override
1108
  public void writeFileContent(String content, Path file, boolean createParentDir) {
1109

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

1128
  @Override
1129
  public List<String> readFileLines(Path file) {
1130

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

1145
  @Override
1146
  public void writeFileLines(List<String> content, Path file, boolean createParentDir) {
1147

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

1166
  @Override
1167
  public void readProperties(Path file, Properties properties) {
1168

1169
    try (Reader reader = Files.newBufferedReader(file)) {
3✔
1170
      properties.load(reader);
3✔
1171
      this.context.debug("Successfully loaded {} properties from {}", properties.size(), file);
16✔
1172
    } catch (IOException e) {
×
1173
      throw new IllegalStateException("Failed to read properties file: " + file, e);
×
1174
    }
1✔
1175
  }
1✔
1176

1177
  @Override
1178
  public void writeProperties(Properties properties, Path file, boolean createParentDir) {
1179

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

1191
  @Override
1192
  public void readIniFile(Path file, IniFile iniFile) {
1193
    if (!Files.exists(file)) {
5!
1194
      this.context.debug("INI file {} does not exist.", iniFile);
×
1195
      return;
×
1196
    }
1197
    List<String> iniLines = readFileLines(file);
4✔
1198
    IniSection currentIniSection = iniFile.getInitialSection();
3✔
1199
    for (String line : iniLines) {
10✔
1200
      if (line.trim().startsWith("[")) {
5✔
1201
        currentIniSection = iniFile.getOrCreateSection(line);
5✔
1202
      } else if (line.isBlank() || IniComment.COMMENT_SYMBOLS.contains(line.trim().charAt(0))) {
11✔
1203
        currentIniSection.addComment(line);
4✔
1204
      } else {
1205
        int index = line.indexOf('=');
4✔
1206
        if (index > 0) {
2!
1207
          currentIniSection.setProperty(line);
3✔
1208
        }
1209
      }
1210
    }
1✔
1211
  }
1✔
1212

1213
  @Override
1214
  public void writeIniFile(IniFile iniFile, Path file, boolean createParentDir) {
1215
    String iniString = iniFile.toString();
3✔
1216
    writeFileContent(iniString, file, createParentDir);
5✔
1217
  }
1✔
1218

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

1235
  @Override
1236
  public boolean isFileAgeRecent(Path path, Duration cacheDuration) {
1237

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