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

devonfw / IDEasy / 15932029172

27 Jun 2025 05:13PM UTC coverage: 68.261% (+0.009%) from 68.252%
15932029172

Pull #1348

github

web-flow
Merge 4dc00b327 into 98d1ed4f3
Pull Request #1348: #1331: add parser for .ini files

3257 of 5184 branches covered (62.83%)

Branch coverage included in aggregate %.

8316 of 11770 relevant lines covered (70.65%)

3.13 hits per line

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

68.14
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
      // errors in reading the attributes of the file
271
      throw new IllegalStateException("An unexpected error occurred whilst checking if the file: " + path + " is a junction", e);
×
272
    }
273
  }
274

275
  @Override
276
  public Path backup(Path fileOrFolder) {
277

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

298
  private static Path appendParentPath(Path path, Path parent, int max) {
299

300
    if ((parent == null) || (max <= 0)) {
4!
301
      return path;
2✔
302
    }
303
    return appendParentPath(path, parent.getParent(), max - 1).resolve(parent.getFileName());
11✔
304
  }
305

306
  @Override
307
  public void move(Path source, Path targetDir, StandardCopyOption... copyOptions) {
308

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

322
  @Override
323
  public void copy(Path source, Path target, FileCopyMode mode, PathCopyListener listener) {
324

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

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

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

391
  /**
392
   * 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
393
   * {@link Path} that is neither a symbolic link nor a Windows junction.
394
   *
395
   * @param path the {@link Path} to delete.
396
   * @throws IOException if the actual {@link Files#delete(Path) deletion} fails.
397
   */
398
  private void deleteLinkIfExists(Path path) throws IOException {
399

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

403
    assert !(isSymlink && isJunction);
5!
404

405
    if (isJunction || isSymlink) {
4!
406
      this.context.info("Deleting previous " + (isJunction ? "junction" : "symlink") + " at " + path);
9!
407
      Files.delete(path);
2✔
408
    }
409
  }
1✔
410

411
  /**
412
   * Adapts the given {@link Path} to be relative or absolute depending on the given {@code relative} flag. Additionally, {@link Path#toRealPath(LinkOption...)}
413
   * is applied to {@code source}.
414
   *
415
   * @param source the {@link Path} to adapt.
416
   * @param targetLink the {@link Path} used to calculate the relative path to the {@code source} if {@code relative} is set to {@code true}.
417
   * @param relative the {@code relative} flag.
418
   * @return the adapted {@link Path}.
419
   * @see FileAccessImpl#symlink(Path, Path, boolean)
420
   */
421
  private Path adaptPath(Path source, Path targetLink, boolean relative) throws IOException {
422

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

451
  /**
452
   * Creates a Windows junction at {@code targetLink} pointing to {@code source}.
453
   *
454
   * @param source must be another Windows junction or a directory.
455
   * @param targetLink the location of the Windows junction.
456
   */
457
  private void createWindowsJunction(Path source, Path targetLink) {
458

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

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

482
  @Override
483
  public void symlink(Path source, Path targetLink, boolean relative) {
484

485
    Path adaptedSource = null;
2✔
486
    try {
487
      adaptedSource = adaptPath(source, targetLink, relative);
6✔
488
    } catch (IOException e) {
×
489
      throw new IllegalStateException("Failed to adapt source for source (" + source + ") target (" + targetLink + ") and relative (" + relative + ")", e);
×
490
    }
1✔
491
    this.context.debug("Creating {} symbolic link {} pointing to {}", adaptedSource.isAbsolute() ? "" : "relative", targetLink, adaptedSource);
23✔
492

493
    try {
494
      deleteLinkIfExists(targetLink);
3✔
495
    } catch (IOException e) {
×
496
      throw new IllegalStateException("Failed to delete previous symlink or Windows junction at " + targetLink, e);
×
497
    }
1✔
498

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

516
  @Override
517
  public Path toRealPath(Path path) {
518

519
    return toRealPath(path, true);
5✔
520
  }
521

522
  @Override
523
  public Path toCanonicalPath(Path path) {
524

525
    return toRealPath(path, false);
5✔
526
  }
527

528
  private Path toRealPath(Path path, boolean resolveLinks) {
529

530
    try {
531
      Path realPath;
532
      if (resolveLinks) {
2✔
533
        realPath = path.toRealPath();
6✔
534
      } else {
535
        realPath = path.toRealPath(LinkOption.NOFOLLOW_LINKS);
9✔
536
      }
537
      if (!realPath.equals(path)) {
4✔
538
        this.context.trace("Resolved path {} to {}", path, realPath);
14✔
539
      }
540
      return realPath;
2✔
541
    } catch (IOException e) {
×
542
      throw new IllegalStateException("Failed to get real path for " + path, e);
×
543
    }
544
  }
545

546
  @Override
547
  public Path createTempDir(String name) {
548

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

567
  @Override
568
  public void extract(Path archiveFile, Path targetDir, Consumer<Path> postExtractHook, boolean extract) {
569

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

610
  private void postExtractHook(Consumer<Path> postExtractHook, Path properInstallDir) {
611

612
    if (postExtractHook != null) {
2✔
613
      postExtractHook.accept(properInstallDir);
3✔
614
    }
615
  }
1✔
616

617
  /**
618
   * @param path the {@link Path} to start the recursive search from.
619
   * @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
620
   *     item in their respective directory and {@code s} is not named "bin".
621
   */
622
  private Path getProperInstallationSubDirOf(Path path, Path archiveFile) {
623

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

641
  @Override
642
  public void extractZip(Path file, Path targetDir) {
643

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

661
  @SuppressWarnings("unchecked")
662
  private void onFileCopiedFromZip(Path source, Path target, boolean directory, IdeProgressBar progressBar) {
663

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

680
  @Override
681
  public void extractTar(Path file, Path targetDir, TarCompression compression) {
682

683
    extractArchive(file, targetDir, in -> new TarArchiveInputStream(compression.unpack(in)));
13✔
684
  }
1✔
685

686
  @Override
687
  public void extractJar(Path file, Path targetDir) {
688

689
    extractZip(file, targetDir);
4✔
690
  }
1✔
691

692
  /**
693
   * @param permissions The integer as returned by {@link TarArchiveEntry#getMode()} that represents the file permissions of a file on a Unix file system.
694
   * @return A String representing the file permissions. E.g. "rwxrwxr-x" or "rw-rw-r--"
695
   */
696
  public static String generatePermissionString(int permissions) {
697

698
    // Ensure that only the last 9 bits are considered
699
    permissions &= 0b111111111;
4✔
700

701
    StringBuilder permissionStringBuilder = new StringBuilder("rwxrwxrwx");
5✔
702
    for (int i = 0; i < 9; i++) {
7✔
703
      int mask = 1 << i;
4✔
704
      char currentChar = ((permissions & mask) != 0) ? permissionStringBuilder.charAt(8 - i) : '-';
12✔
705
      permissionStringBuilder.setCharAt(8 - i, currentChar);
6✔
706
    }
707

708
    return permissionStringBuilder.toString();
3✔
709
  }
710

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

713
    this.context.info("Extracting TAR file {} to {}", file, targetDir);
14✔
714
    try (InputStream is = Files.newInputStream(file);
5✔
715
        ArchiveInputStream<?> ais = unpacker.apply(is);
5✔
716
        IdeProgressBar pb = this.context.newProgressbarForExtracting(getFileSize(file))) {
7✔
717

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

750
  @Override
751
  public void extractDmg(Path file, Path targetDir) {
752

753
    this.context.info("Extracting DMG file {} to {}", file, targetDir);
×
754
    assert this.context.getSystemInfo().isMac();
×
755

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

767
    copy(appPath, targetDir, FileCopyMode.COPY_TREE_OVERRIDE_TREE);
×
768
    pc.addArgs("detach", "-force", mountPath);
×
769
    pc.run();
×
770
  }
×
771

772
  @Override
773
  public void extractMsi(Path file, Path targetDir) {
774

775
    this.context.info("Extracting MSI file {} to {}", file, targetDir);
×
776
    this.context.newProcess().executable("msiexec").addArgs("/a", file, "/qn", "TARGETDIR=" + targetDir).run();
×
777
    // msiexec also creates a copy of the MSI
778
    Path msiCopy = targetDir.resolve(file.getFileName());
×
779
    delete(msiCopy);
×
780
  }
×
781

782
  @Override
783
  public void extractPkg(Path file, Path targetDir) {
784

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

795
  @Override
796
  public void delete(Path path) {
797

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

814
  private void deleteRecursive(Path path) throws IOException {
815

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

833
  @Override
834
  public Path findFirst(Path dir, Predicate<Path> filter, boolean recursive) {
835

836
    try {
837
      if (!Files.isDirectory(dir)) {
5✔
838
        return null;
2✔
839
      }
840
      return findFirstRecursive(dir, filter, recursive);
6✔
841
    } catch (IOException e) {
×
842
      throw new IllegalStateException("Failed to search for file in " + dir, e);
×
843
    }
844
  }
845

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

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

874
  @Override
875
  public List<Path> listChildrenMapped(Path dir, Function<Path, Path> filter) {
876

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

903
  @Override
904
  public boolean isEmptyDir(Path dir) {
905

906
    return listChildren(dir, f -> true).isEmpty();
8✔
907
  }
908

909
  private long getFileSize(Path file) {
910

911
    try {
912
      return Files.size(file);
3✔
913
    } catch (IOException e) {
×
914
      this.context.warning(e.getMessage(), e);
×
915
      return 0;
×
916
    }
917
  }
918

919
  private long getFileSizeRecursive(Path path) {
920

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

938
  @Override
939
  public Path findExistingFile(String fileName, List<Path> searchDirs) {
940

941
    for (Path dir : searchDirs) {
10!
942
      Path filePath = dir.resolve(fileName);
4✔
943
      try {
944
        if (Files.exists(filePath)) {
5✔
945
          return filePath;
2✔
946
        }
947
      } catch (Exception e) {
×
948
        throw new IllegalStateException("Unexpected error while checking existence of file " + filePath + " .", e);
×
949
      }
1✔
950
    }
1✔
951
    return null;
×
952
  }
953

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

973
      // Windows
974
      DosFileAttributeView dos = Files.getFileAttributeView(file, DosFileAttributeView.class);
×
975
      if (dos != null) {
×
976
        dos.setReadOnly(!writable);
×
977
        return true;
×
978
      }
979

980
      this.context.debug("Failed to set writing permission for file {}", file);
×
981
      return false;
×
982

983
    } catch (IOException e) {
×
984
      this.context.debug("Error occurred when trying to set writing permission for file " + file + ": " + e);
×
985
      return false;
×
986
    }
987
  }
988

989
  @Override
990
  public void makeExecutable(Path file, boolean confirm) {
991

992
    if (Files.exists(file)) {
5✔
993
      if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
994
        this.context.trace("Windows does not have executable flags hence omitting for file {}", file);
×
995
        return;
×
996
      }
997
      try {
998
        // Read the current file permissions
999
        Set<PosixFilePermission> existingPermissions = Files.getPosixFilePermissions(file);
5✔
1000

1001
        // Add execute permission for all users
1002
        Set<PosixFilePermission> executablePermissions = new HashSet<>(existingPermissions);
5✔
1003
        boolean update = false;
2✔
1004
        update |= executablePermissions.add(PosixFilePermission.OWNER_EXECUTE);
6✔
1005
        update |= executablePermissions.add(PosixFilePermission.GROUP_EXECUTE);
6✔
1006
        update |= executablePermissions.add(PosixFilePermission.OTHERS_EXECUTE);
6✔
1007

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

1037
  @Override
1038
  public void touch(Path file) {
1039

1040
    if (Files.exists(file)) {
5✔
1041
      try {
1042
        Files.setLastModifiedTime(file, FileTime.fromMillis(System.currentTimeMillis()));
5✔
1043
      } catch (IOException e) {
×
1044
        throw new IllegalStateException("Could not update modification-time of " + file, e);
×
1045
      }
1✔
1046
    } else {
1047
      try {
1048
        Files.createFile(file);
5✔
1049
      } catch (IOException e) {
1✔
1050
        throw new IllegalStateException("Could not create empty file " + file, e);
8✔
1051
      }
1✔
1052
    }
1053
  }
1✔
1054

1055
  @Override
1056
  public String readFileContent(Path file) {
1057

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

1072
  @Override
1073
  public void writeFileContent(String content, Path file, boolean createParentDir) {
1074

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

1093
  @Override
1094
  public List<String> readFileLines(Path file) {
1095

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

1110
  @Override
1111
  public void writeFileLines(List<String> content, Path file, boolean createParentDir) {
1112

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

1131
  @Override
1132
  public void readProperties(Path file, Properties properties) {
1133

1134
    try (Reader reader = Files.newBufferedReader(file)) {
3✔
1135
      properties.load(reader);
3✔
1136
      this.context.debug("Successfully loaded {} properties from {}", properties.size(), file);
16✔
1137
    } catch (IOException e) {
×
1138
      throw new IllegalStateException("Failed to read properties file: " + file, e);
×
1139
    }
1✔
1140
  }
1✔
1141

1142
  @Override
1143
  public void writeProperties(Properties properties, Path file, boolean createParentDir) {
1144

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

1156
  @Override
1157
  public void readIniFile(Path file, IniFile iniFile) {
1158
    List<String> iniLines = readFileLines(file);
4✔
1159
    IniSection currentIniSection = null;
2✔
1160
    for (String line : iniLines) {
10✔
1161
      if (line.isEmpty()) {
3!
1162
        continue;
×
1163
      }
1164
      if (line.startsWith("[")) {
4✔
1165
        String sectionName = line.replace("[", "").replace("]", "");
8✔
1166
        currentIniSection = iniFile.getOrCreateSection(sectionName);
4✔
1167
      } else {
1✔
1168
        int index = line.indexOf('=');
4✔
1169
        if (index > 0) {
2!
1170
          String propertyName = line.substring(0, index).trim();
6✔
1171
          String propertyValue = line.substring(index + 1).trim();
7✔
1172
          if (currentIniSection == null) {
2!
1173
            Log.warn("Invalid ini-file with property {} before section", propertyName);
×
1174
          } else {
1175
            currentIniSection.getProperties().put(propertyName, propertyValue);
6✔
1176
          }  
1177
        } else {
1178
          // here we can handle comments and empty lines in the future
1179
        }
1180
      }
1181
    }
1✔
1182
  }
1✔
1183

1184
  @Override
1185
  public void writeIniFile(IniFile iniFile, Path file, boolean createParentDir) {
1186
    String iniString = iniFile.toString();
3✔
1187
    writeFileContent(iniString, file, createParentDir);
5✔
1188
  }
1✔
1189

1190
  @Override
1191
  public Duration getFileAge(Path path) {
1192
    if (Files.exists(path)) {
5✔
1193
      try {
1194
        long currentTime = System.currentTimeMillis();
2✔
1195
        long fileModifiedTime = Files.getLastModifiedTime(path).toMillis();
6✔
1196
        return Duration.ofMillis(currentTime - fileModifiedTime);
5✔
1197
      } catch (IOException e) {
×
1198
        this.context.warning().log(e, "Could not get modification-time of {}.", path);
×
1199
      }
×
1200
    } else {
1201
      this.context.debug("Path {} is missing - skipping modification-time and file age check.", path);
10✔
1202
    }
1203
    return null;
2✔
1204
  }
1205

1206
  @Override
1207
  public boolean isFileAgeRecent(Path path, Duration cacheDuration) {
1208

1209
    Duration age = getFileAge(path);
4✔
1210
    if (age == null) {
2✔
1211
      return false;
2✔
1212
    }
1213
    context.debug("The path {} was last updated {} ago and caching duration is {}.", path, age, cacheDuration);
18✔
1214
    return (age.toMillis() <= cacheDuration.toMillis());
10✔
1215
  }
1216
}
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