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

devonfw / IDEasy / 16992639699

15 Aug 2025 02:54PM UTC coverage: 69.372% (-0.1%) from 69.51%
16992639699

push

github

web-flow
#1451: fix merge:id default for single attribute (#1452)

3362 of 5289 branches covered (63.57%)

Branch coverage included in aggregate %.

8731 of 12143 relevant lines covered (71.9%)

3.16 hits per line

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

67.05
cli/src/main/java/com/devonfw/tools/ide/io/FileAccessImpl.java
1
package com.devonfw.tools.ide.io;
2

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

48
import org.apache.commons.compress.archivers.ArchiveEntry;
49
import org.apache.commons.compress.archivers.ArchiveInputStream;
50
import org.apache.commons.compress.archivers.ArchiveOutputStream;
51
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
52
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
53
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
54
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
55
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;
56
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
57
import org.apache.commons.io.IOUtils;
58
import org.jline.utils.Log;
59

60
import com.devonfw.tools.ide.cli.CliException;
61
import com.devonfw.tools.ide.cli.CliOfflineException;
62
import com.devonfw.tools.ide.context.IdeContext;
63
import com.devonfw.tools.ide.io.ini.IniComment;
64
import com.devonfw.tools.ide.io.ini.IniFile;
65
import com.devonfw.tools.ide.io.ini.IniSection;
66
import com.devonfw.tools.ide.os.SystemInfoImpl;
67
import com.devonfw.tools.ide.process.ProcessContext;
68
import com.devonfw.tools.ide.util.DateTimeUtil;
69
import com.devonfw.tools.ide.util.FilenameUtil;
70
import com.devonfw.tools.ide.util.HexUtil;
71
import com.devonfw.tools.ide.variable.IdeVariables;
72

73
/**
74
 * Implementation of {@link FileAccess}.
75
 */
76
public class FileAccessImpl implements FileAccess {
77

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

80
  private static final String WINDOWS_FILE_LOCK_WARNING =
81
      "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"
82
          + WINDOWS_FILE_LOCK_DOCUMENTATION_PAGE;
83

84
  private static final int MODE_RWX_RX_RX = 0755;
85
  private static final int MODE_RW_R_R = 0644;
86

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

89
  private final IdeContext context;
90

91
  /**
92
   * The constructor.
93
   *
94
   * @param context the {@link IdeContext} to use.
95
   */
96
  public FileAccessImpl(IdeContext context) {
97

98
    super();
2✔
99
    this.context = context;
3✔
100
  }
1✔
101

102
  private HttpClient createHttpClient(String url) {
103

104
    return HttpClient.newBuilder().followRedirects(Redirect.ALWAYS).build();
5✔
105
  }
106

107
  @Override
108
  public void download(String url, Path target) {
109

110
    if (this.context.isOffline()) {
4!
111
      throw CliOfflineException.ofDownloadViaUrl(url);
×
112
    }
113
    if (url.startsWith("http")) {
4✔
114
      downloadViaHttp(url, target);
5✔
115
    } else if (url.startsWith("ftp") || url.startsWith("sftp")) {
8!
116
      throw new IllegalArgumentException("Unsupported download URL: " + url);
×
117
    } else {
118
      Path source = Path.of(url);
5✔
119
      if (isFile(source)) {
4!
120
        // network drive
121
        copyFileWithProgressBar(source, target);
5✔
122
      } else {
123
        throw new IllegalArgumentException("Download path does not point to a downloadable file: " + url);
×
124
      }
125
    }
126
  }
1✔
127

128
  private void downloadViaHttp(String url, Path target) {
129
    List<Version> httpProtocols = IdeVariables.HTTP_VERSIONS.get(context);
6✔
130
    Exception lastException = null;
2✔
131
    if (httpProtocols.isEmpty()) {
3!
132
      try {
133
        this.downloadWithHttpVersion(url, target, null);
5✔
134
        return;
1✔
135
      } catch (Exception e) {
×
136
        lastException = e;
×
137
      }
×
138
    } else {
139
      for (Version version : httpProtocols) {
×
140
        try {
141
          this.downloadWithHttpVersion(url, target, version);
×
142
          return;
×
143
        } catch (Exception ex) {
×
144
          lastException = ex;
×
145
        }
146
      }
×
147
    }
148
    throw new IllegalStateException("Failed to download file from URL " + url + " to " + target, lastException);
×
149
  }
150

151
  private void downloadWithHttpVersion(String url, Path target, Version httpVersion) throws Exception {
152

153
    if (httpVersion == null) {
2!
154
      this.context.info("Trying to download {} from {}", target.getFileName(), url);
16✔
155
    } else {
156
      this.context.info("Trying to download: {} with HTTP protocol version: {}", url, httpVersion);
×
157
    }
158
    mkdirs(target.getParent());
4✔
159

160
    Builder builder = HttpRequest.newBuilder()
2✔
161
        .uri(URI.create(url))
2✔
162
        .GET();
2✔
163
    if (httpVersion != null) {
2!
164
      builder.version(httpVersion);
×
165
    }
166
    try (HttpClient client = createHttpClient(url)) {
4✔
167
      HttpRequest request = builder.build();
3✔
168
      HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
5✔
169
      int statusCode = response.statusCode();
3✔
170
      if (statusCode == 200) {
3!
171
        downloadFileWithProgressBar(url, target, response);
6✔
172
      } else {
173
        throw new IllegalStateException("Download failed with status code " + statusCode);
×
174
      }
175
    }
176
  }
1✔
177

178
  /**
179
   * Downloads a file while showing a {@link IdeProgressBar}.
180
   *
181
   * @param url the url to download.
182
   * @param target Path of the target directory.
183
   * @param response the {@link HttpResponse} to use.
184
   */
185
  private void downloadFileWithProgressBar(String url, Path target, HttpResponse<InputStream> response) {
186

187
    long contentLength = response.headers().firstValueAsLong("content-length").orElse(-1);
7✔
188
    informAboutMissingContentLength(contentLength, url);
4✔
189

190
    byte[] data = new byte[1024];
3✔
191
    boolean fileComplete = false;
2✔
192
    int count;
193

194
    try (InputStream body = response.body();
4✔
195
        FileOutputStream fileOutput = new FileOutputStream(target.toFile());
6✔
196
        BufferedOutputStream bufferedOut = new BufferedOutputStream(fileOutput, data.length);
7✔
197
        IdeProgressBar pb = this.context.newProgressBarForDownload(contentLength)) {
5✔
198
      while (!fileComplete) {
2✔
199
        count = body.read(data);
4✔
200
        if (count <= 0) {
2✔
201
          fileComplete = true;
3✔
202
        } else {
203
          bufferedOut.write(data, 0, count);
5✔
204
          pb.stepBy(count);
5✔
205
        }
206
      }
207

208
    } catch (Exception e) {
×
209
      throw new RuntimeException(e);
×
210
    }
1✔
211
  }
1✔
212

213
  private void copyFileWithProgressBar(Path source, Path target) {
214

215
    long size = getFileSize(source);
4✔
216
    if (size < 100_000) {
4✔
217
      copy(source, target, FileCopyMode.COPY_FILE_TO_TARGET_OVERRIDE);
5✔
218
      return;
1✔
219
    }
220
    try (InputStream in = Files.newInputStream(source);
5✔
221
        OutputStream out = Files.newOutputStream(target)) {
5✔
222
      byte[] buf = new byte[1024];
3✔
223
      try (IdeProgressBar pb = this.context.newProgressbarForCopying(size)) {
5✔
224
        int readBytes;
225
        while ((readBytes = in.read(buf)) > 0) {
6✔
226
          out.write(buf, 0, readBytes);
5✔
227
          pb.stepBy(readBytes);
5✔
228
        }
229
      } catch (Exception e) {
×
230
        throw new RuntimeException(e);
×
231
      }
1✔
232
    } catch (IOException e) {
×
233
      throw new RuntimeException("Failed to copy from " + source + " to " + target, e);
×
234
    }
1✔
235
  }
1✔
236

237
  private void informAboutMissingContentLength(long contentLength, String url) {
238

239
    if (contentLength < 0) {
4✔
240
      this.context.warning("Content-Length was not provided by download from {}", url);
10✔
241
    }
242
  }
1✔
243

244
  @Override
245
  public void mkdirs(Path directory) {
246

247
    if (Files.isDirectory(directory)) {
5✔
248
      return;
1✔
249
    }
250
    this.context.trace("Creating directory {}", directory);
10✔
251
    try {
252
      Files.createDirectories(directory);
5✔
253
    } catch (IOException e) {
×
254
      throw new IllegalStateException("Failed to create directory " + directory, e);
×
255
    }
1✔
256
  }
1✔
257

258
  @Override
259
  public boolean isFile(Path file) {
260

261
    if (!Files.exists(file)) {
5!
262
      this.context.trace("File {} does not exist", file);
×
263
      return false;
×
264
    }
265
    if (Files.isDirectory(file)) {
5!
266
      this.context.trace("Path {} is a directory but a regular file was expected", file);
×
267
      return false;
×
268
    }
269
    return true;
2✔
270
  }
271

272
  @Override
273
  public boolean isExpectedFolder(Path folder) {
274

275
    if (Files.isDirectory(folder)) {
5✔
276
      return true;
2✔
277
    }
278
    this.context.warning("Expected folder was not found at {}", folder);
10✔
279
    return false;
2✔
280
  }
281

282
  @Override
283
  public String checksum(Path file, String hashAlgorithm) {
284

285
    MessageDigest md;
286
    try {
287
      md = MessageDigest.getInstance(hashAlgorithm);
×
288
    } catch (NoSuchAlgorithmException e) {
×
289
      throw new IllegalStateException("No such hash algorithm " + hashAlgorithm, e);
×
290
    }
×
291
    byte[] buffer = new byte[1024];
×
292
    try (InputStream is = Files.newInputStream(file); DigestInputStream dis = new DigestInputStream(is, md)) {
×
293
      int read = 0;
×
294
      while (read >= 0) {
×
295
        read = dis.read(buffer);
×
296
      }
297
    } catch (Exception e) {
×
298
      throw new IllegalStateException("Failed to read and hash file " + file, e);
×
299
    }
×
300
    byte[] digestBytes = md.digest();
×
301
    return HexUtil.toHexString(digestBytes);
×
302
  }
303

304
  public boolean isJunction(Path path) {
305

306
    if (!SystemInfoImpl.INSTANCE.isWindows()) {
3!
307
      return false;
2✔
308
    }
309

310
    try {
311
      BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
×
312
      return attr.isOther() && attr.isDirectory();
×
313
    } catch (NoSuchFileException e) {
×
314
      return false; // file doesn't exist
×
315
    } catch (IOException e) {
×
316
      // errors in reading the attributes of the file
317
      throw new IllegalStateException("An unexpected error occurred whilst checking if the file: " + path + " is a junction", e);
×
318
    }
319
  }
320

321
  @Override
322
  public Path backup(Path fileOrFolder) {
323

324
    if ((fileOrFolder != null) && (Files.isSymbolicLink(fileOrFolder) || isJunction(fileOrFolder))) {
9!
325
      delete(fileOrFolder);
4✔
326
    } else if ((fileOrFolder != null) && Files.exists(fileOrFolder)) {
7!
327
      LocalDateTime now = LocalDateTime.now();
2✔
328
      String date = DateTimeUtil.formatDate(now, true);
4✔
329
      String time = DateTimeUtil.formatTime(now);
3✔
330
      String filename = fileOrFolder.getFileName().toString();
4✔
331
      Path backupPath = this.context.getIdeHome().resolve(IdeContext.FOLDER_BACKUPS).resolve(date).resolve(time + "_" + filename);
12✔
332
      backupPath = appendParentPath(backupPath, fileOrFolder.getParent(), 2);
6✔
333
      mkdirs(backupPath);
3✔
334
      Path target = backupPath.resolve(filename);
4✔
335
      this.context.info("Creating backup by moving {} to {}", fileOrFolder, target);
14✔
336
      move(fileOrFolder, target);
6✔
337
      return target;
2✔
338
    } else {
339
      this.context.trace("Backup of {} skipped as the path does not exist.", fileOrFolder);
10✔
340
    }
341
    return fileOrFolder;
2✔
342
  }
343

344
  private static Path appendParentPath(Path path, Path parent, int max) {
345

346
    if ((parent == null) || (max <= 0)) {
4!
347
      return path;
2✔
348
    }
349
    return appendParentPath(path, parent.getParent(), max - 1).resolve(parent.getFileName());
11✔
350
  }
351

352
  @Override
353
  public void move(Path source, Path targetDir, StandardCopyOption... copyOptions) {
354

355
    this.context.trace("Moving {} to {}", source, targetDir);
14✔
356
    try {
357
      Files.move(source, targetDir, copyOptions);
5✔
358
    } catch (IOException e) {
×
359
      String fileType = Files.isSymbolicLink(source) ? "symlink" : isJunction(source) ? "junction" : Files.isDirectory(source) ? "directory" : "file";
×
360
      String message = "Failed to move " + fileType + ": " + source + " to " + targetDir + ".";
×
361
      if (this.context.getSystemInfo().isWindows()) {
×
362
        message = message + "\n" + WINDOWS_FILE_LOCK_WARNING;
×
363
      }
364
      throw new IllegalStateException(message, e);
×
365
    }
1✔
366
  }
1✔
367

368
  @Override
369
  public void copy(Path source, Path target, FileCopyMode mode, PathCopyListener listener) {
370

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

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

415
    if (Files.isDirectory(source)) {
5✔
416
      mkdirs(target);
3✔
417
      try (Stream<Path> childStream = Files.list(source)) {
3✔
418
        Iterator<Path> iterator = childStream.iterator();
3✔
419
        while (iterator.hasNext()) {
3✔
420
          Path child = iterator.next();
4✔
421
          copyRecursive(child, target.resolve(child.getFileName().toString()), mode, listener);
10✔
422
        }
1✔
423
      }
424
      listener.onCopy(source, target, true);
6✔
425
    } else if (Files.exists(source)) {
5!
426
      if (mode.isOverride()) {
3✔
427
        delete(target);
3✔
428
      }
429
      this.context.trace("Starting to {} {} to {}", mode.getOperation(), source, target);
19✔
430
      Files.copy(source, target);
6✔
431
      listener.onCopy(source, target, false);
6✔
432
    } else {
433
      throw new IOException("Path " + source + " does not exist.");
×
434
    }
435
  }
1✔
436

437
  /**
438
   * 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
439
   * {@link Path} that is neither a symbolic link nor a Windows junction.
440
   *
441
   * @param path the {@link Path} to delete.
442
   * @throws IOException if the actual {@link Files#delete(Path) deletion} fails.
443
   */
444
  private void deleteLinkIfExists(Path path) throws IOException {
445

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

449
    assert !(isSymlink && isJunction);
5!
450

451
    if (isJunction || isSymlink) {
4!
452
      this.context.info("Deleting previous " + (isJunction ? "junction" : "symlink") + " at " + path);
9!
453
      Files.delete(path);
2✔
454
    }
455
  }
1✔
456

457
  /**
458
   * Adapts the given {@link Path} to be relative or absolute depending on the given {@code relative} flag. Additionally, {@link Path#toRealPath(LinkOption...)}
459
   * is applied to {@code source}.
460
   *
461
   * @param source the {@link Path} to adapt.
462
   * @param targetLink the {@link Path} used to calculate the relative path to the {@code source} if {@code relative} is set to {@code true}.
463
   * @param relative the {@code relative} flag.
464
   * @return the adapted {@link Path}.
465
   * @see FileAccessImpl#symlink(Path, Path, boolean)
466
   */
467
  private Path adaptPath(Path source, Path targetLink, boolean relative) throws IOException {
468

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

497
  /**
498
   * Creates a Windows junction at {@code targetLink} pointing to {@code source}.
499
   *
500
   * @param source must be another Windows junction or a directory.
501
   * @param targetLink the location of the Windows junction.
502
   */
503
  private void createWindowsJunction(Path source, Path targetLink) {
504

505
    this.context.trace("Creating a Windows junction at " + targetLink + " with " + source + " as source.");
×
506
    Path fallbackPath;
507
    if (!source.isAbsolute()) {
×
508
      this.context.warning("You are on Windows and you do not have permissions to create symbolic links. Junctions are used as an "
×
509
          + "alternative, however, these can not point to relative paths. So the source (" + source + ") is interpreted as an absolute path.");
510
      try {
511
        fallbackPath = targetLink.resolveSibling(source).toRealPath(LinkOption.NOFOLLOW_LINKS);
×
512
      } catch (IOException e) {
×
513
        throw new IllegalStateException(
×
514
            "Since Windows junctions are used, the source must be an absolute path. The transformation of the passed " + "source (" + source
515
                + ") to an absolute path failed.", e);
516
      }
×
517

518
    } else {
519
      fallbackPath = source;
×
520
    }
521
    if (!Files.isDirectory(fallbackPath)) { // if source is a junction. This returns true as well.
×
522
      throw new IllegalStateException(
×
523
          "These junctions can only point to directories or other junctions. Please make sure that the source (" + fallbackPath + ") is one of these.");
524
    }
525
    this.context.newProcess().executable("cmd").addArgs("/c", "mklink", "/d", "/j", targetLink.toString(), fallbackPath.toString()).run();
×
526
  }
×
527

528
  @Override
529
  public void symlink(Path source, Path targetLink, boolean relative) {
530

531
    Path adaptedSource = null;
2✔
532
    try {
533
      adaptedSource = adaptPath(source, targetLink, relative);
6✔
534
    } catch (IOException e) {
×
535
      throw new IllegalStateException("Failed to adapt source for source (" + source + ") target (" + targetLink + ") and relative (" + relative + ")", e);
×
536
    }
1✔
537
    this.context.debug("Creating {} symbolic link {} pointing to {}", adaptedSource.isAbsolute() ? "" : "relative", targetLink, adaptedSource);
23✔
538

539
    try {
540
      deleteLinkIfExists(targetLink);
3✔
541
    } catch (IOException e) {
×
542
      throw new IllegalStateException("Failed to delete previous symlink or Windows junction at " + targetLink, e);
×
543
    }
1✔
544

545
    try {
546
      Files.createSymbolicLink(targetLink, adaptedSource);
6✔
547
    } catch (FileSystemException e) {
×
548
      if (SystemInfoImpl.INSTANCE.isWindows()) {
×
549
        this.context.info("Due to lack of permissions, Microsoft's mklink with junction had to be used to create "
×
550
            + "a Symlink. See https://github.com/devonfw/IDEasy/blob/main/documentation/symlink.adoc for " + "further details. Error was: "
551
            + e.getMessage());
×
552
        createWindowsJunction(adaptedSource, targetLink);
×
553
      } else {
554
        throw new RuntimeException(e);
×
555
      }
556
    } catch (IOException e) {
×
557
      throw new IllegalStateException(
×
558
          "Failed to create a " + (adaptedSource.isAbsolute() ? "" : "relative") + "symbolic link " + targetLink + " pointing to " + source, e);
×
559
    }
1✔
560
  }
1✔
561

562
  @Override
563
  public Path toRealPath(Path path) {
564

565
    return toRealPath(path, true);
5✔
566
  }
567

568
  @Override
569
  public Path toCanonicalPath(Path path) {
570

571
    return toRealPath(path, false);
5✔
572
  }
573

574
  private Path toRealPath(Path path, boolean resolveLinks) {
575

576
    try {
577
      Path realPath;
578
      if (resolveLinks) {
2✔
579
        realPath = path.toRealPath();
6✔
580
      } else {
581
        realPath = path.toRealPath(LinkOption.NOFOLLOW_LINKS);
9✔
582
      }
583
      if (!realPath.equals(path)) {
4✔
584
        this.context.trace("Resolved path {} to {}", path, realPath);
14✔
585
      }
586
      return realPath;
2✔
587
    } catch (IOException e) {
×
588
      throw new IllegalStateException("Failed to get real path for " + path, e);
×
589
    }
590
  }
591

592
  @Override
593
  public Path createTempDir(String name) {
594

595
    try {
596
      Path tmp = this.context.getTempPath();
4✔
597
      Path tempDir = tmp.resolve(name);
4✔
598
      int tries = 1;
2✔
599
      while (Files.exists(tempDir)) {
5!
600
        long id = System.nanoTime() & 0xFFFF;
×
601
        tempDir = tmp.resolve(name + "-" + id);
×
602
        tries++;
×
603
        if (tries > 200) {
×
604
          throw new IOException("Unable to create unique name!");
×
605
        }
606
      }
×
607
      return Files.createDirectory(tempDir);
5✔
608
    } catch (IOException e) {
×
609
      throw new IllegalStateException("Failed to create temporary directory with prefix '" + name + "'!", e);
×
610
    }
611
  }
612

613
  @Override
614
  public void extract(Path archiveFile, Path targetDir, Consumer<Path> postExtractHook, boolean extract) {
615

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

654
  private void postExtractHook(Consumer<Path> postExtractHook, Path properInstallDir) {
655

656
    if (postExtractHook != null) {
2✔
657
      postExtractHook.accept(properInstallDir);
3✔
658
    }
659
  }
1✔
660

661
  /**
662
   * @param path the {@link Path} to start the recursive search from.
663
   * @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
664
   *     item in their respective directory and {@code s} is not named "bin".
665
   */
666
  private Path getProperInstallationSubDirOf(Path path, Path archiveFile) {
667

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

685
  @Override
686
  public void extractZip(Path file, Path targetDir) {
687

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

705
  @SuppressWarnings("unchecked")
706
  private void onFileCopiedFromZip(Path source, Path target, boolean directory, IdeProgressBar progressBar) {
707

708
    if (directory) {
2✔
709
      return;
1✔
710
    }
711
    if (!context.getSystemInfo().isWindows()) {
5✔
712
      try {
713
        Object attribute = Files.getAttribute(source, "zip:permissions");
6✔
714
        if (attribute instanceof Set<?> permissionSet) {
6✔
715
          Files.setPosixFilePermissions(target, (Set<PosixFilePermission>) permissionSet);
4✔
716
        }
717
      } catch (Exception e) {
×
718
        context.error(e, "Failed to transfer zip permissions for {}", target);
×
719
      }
1✔
720
    }
721
    progressBar.stepBy(getFileSize(target));
5✔
722
  }
1✔
723

724
  @Override
725
  public void extractTar(Path file, Path targetDir, TarCompression compression) {
726

727
    extractArchive(file, targetDir, in -> new TarArchiveInputStream(compression.unpack(in)));
13✔
728
  }
1✔
729

730
  @Override
731
  public void extractJar(Path file, Path targetDir) {
732

733
    extractZip(file, targetDir);
4✔
734
  }
1✔
735

736
  /**
737
   * @param permissions The integer as returned by {@link TarArchiveEntry#getMode()} that represents the file permissions of a file on a Unix file system.
738
   * @return A String representing the file permissions. E.g. "rwxrwxr-x" or "rw-rw-r--"
739
   */
740
  public static String generatePermissionString(int permissions) {
741

742
    // Ensure that only the last 9 bits are considered
743
    permissions &= 0b111111111;
4✔
744

745
    StringBuilder permissionStringBuilder = new StringBuilder("rwxrwxrwx");
5✔
746
    for (int i = 0; i < 9; i++) {
7✔
747
      int mask = 1 << i;
4✔
748
      char currentChar = ((permissions & mask) != 0) ? permissionStringBuilder.charAt(8 - i) : '-';
12✔
749
      permissionStringBuilder.setCharAt(8 - i, currentChar);
6✔
750
    }
751

752
    return permissionStringBuilder.toString();
3✔
753
  }
754

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

757
    this.context.info("Extracting TAR file {} to {}", file, targetDir);
14✔
758
    try (InputStream is = Files.newInputStream(file);
5✔
759
        ArchiveInputStream<?> ais = unpacker.apply(is);
5✔
760
        IdeProgressBar pb = this.context.newProgressbarForExtracting(getFileSize(file))) {
7✔
761

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

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

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

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

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

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

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

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

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

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

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

853
  @Override
854
  public void compressTar(Path dir, OutputStream out, TarCompression tarCompression) {
855
    switch (tarCompression) {
8!
856
      case null -> compressTar(dir, out);
×
857
      case NONE -> compressTar(dir, out);
×
858
      case GZ -> compressTarGz(dir, out);
5✔
859
      case BZIP2 -> compressTarBzip2(dir, out);
×
860
      default -> throw new IllegalArgumentException("Unsupported tar compression: " + tarCompression);
×
861
    }
862
  }
1✔
863

864
  @Override
865
  public void compressTarGz(Path dir, OutputStream out) {
866
    try (GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(out)) {
5✔
867
      compressTarOrThrow(dir, gzOut);
4✔
868
    } catch (IOException e) {
×
869
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar.gz file.", e);
×
870
    }
1✔
871
  }
1✔
872

873
  @Override
874
  public void compressTarBzip2(Path dir, OutputStream out) {
875
    try (BZip2CompressorOutputStream bzip2Out = new BZip2CompressorOutputStream(out)) {
×
876
      compressTarOrThrow(dir, bzip2Out);
×
877
    } catch (IOException e) {
×
878
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar.bz2 file.", e);
×
879
    }
×
880
  }
×
881

882
  @Override
883
  public void compressTar(Path dir, OutputStream out) {
884
    try {
885
      compressTarOrThrow(dir, out);
×
886
    } catch (IOException e) {
×
887
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar file.", e);
×
888
    }
×
889
  }
×
890

891
  private void compressTarOrThrow(Path dir, OutputStream out) throws IOException {
892
    try (TarArchiveOutputStream tarOut = new TarArchiveOutputStream(out)) {
5✔
893
      compressRecursive(dir, tarOut, "");
5✔
894
      tarOut.finish();
2✔
895
    }
896
  }
1✔
897

898
  @Override
899
  public void compressZip(Path dir, OutputStream out) {
900
    try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(out)) {
×
901
      compressRecursive(dir, zipOut, "");
×
902
      zipOut.finish();
×
903
    } catch (IOException e) {
×
904
      throw new IllegalStateException("Failed to compress directory " + dir + " to zip file.", e);
×
905
    }
×
906
  }
×
907

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

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

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

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

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

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

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

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

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

1031
  @Override
1032
  public List<Path> listChildrenMapped(Path dir, Function<Path, Path> filter) {
1033

1034
    if (!Files.isDirectory(dir)) {
5✔
1035
      return List.of();
2✔
1036
    }
1037
    List<Path> children = new ArrayList<>();
4✔
1038
    try (Stream<Path> childStream = Files.list(dir)) {
3✔
1039
      Iterator<Path> iterator = childStream.iterator();
3✔
1040
      while (iterator.hasNext()) {
3✔
1041
        Path child = iterator.next();
4✔
1042
        Path filteredChild = filter.apply(child);
5✔
1043
        if (filteredChild != null) {
2✔
1044
          if (filteredChild == child) {
3!
1045
            this.context.trace("Accepted file {}", child);
11✔
1046
          } else {
1047
            this.context.trace("Accepted file {} and mapped to {}", child, filteredChild);
×
1048
          }
1049
          children.add(filteredChild);
5✔
1050
        } else {
1051
          this.context.trace("Ignoring file {} according to filter", child);
10✔
1052
        }
1053
      }
1✔
1054
    } catch (IOException e) {
×
1055
      throw new IllegalStateException("Failed to find children of directory " + dir, e);
×
1056
    }
1✔
1057
    return children;
2✔
1058
  }
1059

1060
  @Override
1061
  public boolean isEmptyDir(Path dir) {
1062

1063
    return listChildren(dir, f -> true).isEmpty();
8✔
1064
  }
1065

1066
  private long getFileSize(Path file) {
1067

1068
    try {
1069
      return Files.size(file);
3✔
1070
    } catch (IOException e) {
×
1071
      this.context.warning(e.getMessage(), e);
×
1072
      return 0;
×
1073
    }
1074
  }
1075

1076
  private long getFileSizeRecursive(Path path) {
1077

1078
    long size = 0;
2✔
1079
    if (Files.isDirectory(path)) {
5✔
1080
      try (Stream<Path> childStream = Files.list(path)) {
3✔
1081
        Iterator<Path> iterator = childStream.iterator();
3✔
1082
        while (iterator.hasNext()) {
3✔
1083
          Path child = iterator.next();
4✔
1084
          size += getFileSizeRecursive(child);
6✔
1085
        }
1✔
1086
      } catch (IOException e) {
×
1087
        throw new RuntimeException("Failed to iterate children of folder " + path, e);
×
1088
      }
1✔
1089
    } else {
1090
      size += getFileSize(path);
6✔
1091
    }
1092
    return size;
2✔
1093
  }
1094

1095
  @Override
1096
  public Path findExistingFile(String fileName, List<Path> searchDirs) {
1097

1098
    for (Path dir : searchDirs) {
10!
1099
      Path filePath = dir.resolve(fileName);
4✔
1100
      try {
1101
        if (Files.exists(filePath)) {
5✔
1102
          return filePath;
2✔
1103
        }
1104
      } catch (Exception e) {
×
1105
        throw new IllegalStateException("Unexpected error while checking existence of file " + filePath + " .", e);
×
1106
      }
1✔
1107
    }
1✔
1108
    return null;
×
1109
  }
1110

1111
  @Override
1112
  public boolean setWritable(Path file, boolean writable) {
1113
    try {
1114
      // POSIX
1115
      PosixFileAttributeView posix = Files.getFileAttributeView(file, PosixFileAttributeView.class);
7✔
1116
      if (posix != null) {
2!
1117
        Set<PosixFilePermission> permissions = new HashSet<>(posix.readAttributes().permissions());
7✔
1118
        boolean changed;
1119
        if (writable) {
2!
1120
          changed = permissions.add(PosixFilePermission.OWNER_WRITE);
5✔
1121
        } else {
1122
          changed = permissions.remove(PosixFilePermission.OWNER_WRITE);
×
1123
        }
1124
        if (changed) {
2!
1125
          posix.setPermissions(permissions);
×
1126
        }
1127
        return true;
2✔
1128
      }
1129

1130
      // Windows
1131
      DosFileAttributeView dos = Files.getFileAttributeView(file, DosFileAttributeView.class);
×
1132
      if (dos != null) {
×
1133
        dos.setReadOnly(!writable);
×
1134
        return true;
×
1135
      }
1136

1137
      this.context.debug("Failed to set writing permission for file {}", file);
×
1138
      return false;
×
1139

1140
    } catch (IOException e) {
1✔
1141
      this.context.debug("Error occurred when trying to set writing permission for file " + file + ": " + e);
8✔
1142
      return false;
2✔
1143
    }
1144
  }
1145

1146
  @Override
1147
  public void makeExecutable(Path file, boolean confirm) {
1148

1149
    if (Files.exists(file)) {
5✔
1150
      if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
1151
        this.context.trace("Windows does not have executable flags hence omitting for file {}", file);
×
1152
        return;
×
1153
      }
1154
      try {
1155
        // Read the current file permissions
1156
        Set<PosixFilePermission> existingPermissions = Files.getPosixFilePermissions(file);
5✔
1157

1158
        // Add execute permission for all users
1159
        Set<PosixFilePermission> executablePermissions = new HashSet<>(existingPermissions);
5✔
1160
        boolean update = false;
2✔
1161
        update |= executablePermissions.add(PosixFilePermission.OWNER_EXECUTE);
6✔
1162
        update |= executablePermissions.add(PosixFilePermission.GROUP_EXECUTE);
6✔
1163
        update |= executablePermissions.add(PosixFilePermission.OTHERS_EXECUTE);
6✔
1164

1165
        if (update) {
2✔
1166
          if (confirm) {
2!
1167
            boolean yesContinue = this.context.question(
×
1168
                "We want to execute " + file.getFileName() + " but this command seems to lack executable permissions!\n"
×
1169
                    + "Most probably the tool vendor did forgot to add x-flags in the binary release package.\n"
1170
                    + "Before running the command, we suggest to set executable permissions to the file:\n"
1171
                    + file + "\n"
1172
                    + "For security reasons we ask for your confirmation so please check this request.\n"
1173
                    + "Changing permissions from " + PosixFilePermissions.toString(existingPermissions) + " to " + PosixFilePermissions.toString(
×
1174
                    executablePermissions) + ".\n"
1175
                    + "Do you confirm to make the command executable before running it?");
1176
            if (!yesContinue) {
×
1177
              return;
×
1178
            }
1179
          }
1180
          this.context.debug("Setting executable flags for file {}", file);
10✔
1181
          // Set the new permissions
1182
          Files.setPosixFilePermissions(file, executablePermissions);
5✔
1183
        } else {
1184
          this.context.trace("Executable flags already present so no need to set them for file {}", file);
10✔
1185
        }
1186
      } catch (IOException e) {
×
1187
        throw new RuntimeException(e);
×
1188
      }
1✔
1189
    } else {
1190
      this.context.warning("Cannot set executable flag on file that does not exist: {}", file);
10✔
1191
    }
1192
  }
1✔
1193

1194
  @Override
1195
  public void touch(Path file) {
1196

1197
    if (Files.exists(file)) {
5✔
1198
      try {
1199
        Files.setLastModifiedTime(file, FileTime.fromMillis(System.currentTimeMillis()));
5✔
1200
      } catch (IOException e) {
×
1201
        throw new IllegalStateException("Could not update modification-time of " + file, e);
×
1202
      }
1✔
1203
    } else {
1204
      try {
1205
        Files.createFile(file);
5✔
1206
      } catch (IOException e) {
1✔
1207
        throw new IllegalStateException("Could not create empty file " + file, e);
8✔
1208
      }
1✔
1209
    }
1210
  }
1✔
1211

1212
  @Override
1213
  public String readFileContent(Path file) {
1214

1215
    this.context.trace("Reading content of file from {}", file);
10✔
1216
    if (!Files.exists((file))) {
5!
1217
      this.context.debug("File {} does not exist", file);
×
1218
      return null;
×
1219
    }
1220
    try {
1221
      String content = Files.readString(file);
3✔
1222
      this.context.trace("Completed reading {} character(s) from file {}", content.length(), file);
16✔
1223
      return content;
2✔
1224
    } catch (IOException e) {
×
1225
      throw new IllegalStateException("Failed to read file " + file, e);
×
1226
    }
1227
  }
1228

1229
  @Override
1230
  public void writeFileContent(String content, Path file, boolean createParentDir) {
1231

1232
    if (createParentDir) {
2✔
1233
      mkdirs(file.getParent());
4✔
1234
    }
1235
    if (content == null) {
2!
1236
      content = "";
×
1237
    }
1238
    this.context.trace("Writing content with {} character(s) to file {}", content.length(), file);
16✔
1239
    if (Files.exists(file)) {
5✔
1240
      this.context.info("Overriding content of file {}", file);
10✔
1241
    }
1242
    try {
1243
      Files.writeString(file, content);
6✔
1244
      this.context.trace("Wrote content to file {}", file);
10✔
1245
    } catch (IOException e) {
×
1246
      throw new RuntimeException("Failed to write file " + file, e);
×
1247
    }
1✔
1248
  }
1✔
1249

1250
  @Override
1251
  public List<String> readFileLines(Path file) {
1252

1253
    this.context.trace("Reading content of file from {}", file);
10✔
1254
    if (!Files.exists(file)) {
5✔
1255
      this.context.warning("File {} does not exist", file);
10✔
1256
      return null;
2✔
1257
    }
1258
    try {
1259
      List<String> content = Files.readAllLines(file);
3✔
1260
      this.context.trace("Completed reading {} lines from file {}", content.size(), file);
16✔
1261
      return content;
2✔
1262
    } catch (IOException e) {
×
1263
      throw new IllegalStateException("Failed to read file " + file, e);
×
1264
    }
1265
  }
1266

1267
  @Override
1268
  public void writeFileLines(List<String> content, Path file, boolean createParentDir) {
1269

1270
    if (createParentDir) {
2!
1271
      mkdirs(file.getParent());
×
1272
    }
1273
    if (content == null) {
2!
1274
      content = List.of();
×
1275
    }
1276
    this.context.trace("Writing content with {} lines to file {}", content.size(), file);
16✔
1277
    if (Files.exists(file)) {
5✔
1278
      this.context.debug("Overriding content of file {}", file);
10✔
1279
    }
1280
    try {
1281
      Files.write(file, content);
6✔
1282
      this.context.trace("Wrote content to file {}", file);
10✔
1283
    } catch (IOException e) {
×
1284
      throw new RuntimeException("Failed to write file " + file, e);
×
1285
    }
1✔
1286
  }
1✔
1287

1288
  @Override
1289
  public void readProperties(Path file, Properties properties) {
1290

1291
    try (Reader reader = Files.newBufferedReader(file)) {
3✔
1292
      properties.load(reader);
3✔
1293
      this.context.debug("Successfully loaded {} properties from {}", properties.size(), file);
16✔
1294
    } catch (IOException e) {
×
1295
      throw new IllegalStateException("Failed to read properties file: " + file, e);
×
1296
    }
1✔
1297
  }
1✔
1298

1299
  @Override
1300
  public void writeProperties(Properties properties, Path file, boolean createParentDir) {
1301

1302
    if (createParentDir) {
2✔
1303
      mkdirs(file.getParent());
4✔
1304
    }
1305
    try (Writer writer = Files.newBufferedWriter(file)) {
5✔
1306
      properties.store(writer, null); // do not get confused - Java still writes a date/time header that cannot be omitted
4✔
1307
      this.context.debug("Successfully saved {} properties to {}", properties.size(), file);
16✔
1308
    } catch (IOException e) {
×
1309
      throw new IllegalStateException("Failed to save properties file during tests.", e);
×
1310
    }
1✔
1311
  }
1✔
1312

1313
  @Override
1314
  public void readIniFile(Path file, IniFile iniFile) {
1315
    if (!Files.exists(file)) {
5!
1316
      this.context.debug("INI file {} does not exist.", iniFile);
×
1317
      return;
×
1318
    }
1319
    List<String> iniLines = readFileLines(file);
4✔
1320
    IniSection currentIniSection = iniFile.getInitialSection();
3✔
1321
    for (String line : iniLines) {
10✔
1322
      if (line.trim().startsWith("[")) {
5✔
1323
        currentIniSection = iniFile.getOrCreateSection(line);
5✔
1324
      } else if (line.isBlank() || IniComment.COMMENT_SYMBOLS.contains(line.trim().charAt(0))) {
11✔
1325
        currentIniSection.addComment(line);
4✔
1326
      } else {
1327
        int index = line.indexOf('=');
4✔
1328
        if (index > 0) {
2!
1329
          currentIniSection.setProperty(line);
3✔
1330
        }
1331
      }
1332
    }
1✔
1333
  }
1✔
1334

1335
  @Override
1336
  public void writeIniFile(IniFile iniFile, Path file, boolean createParentDir) {
1337
    String iniString = iniFile.toString();
3✔
1338
    writeFileContent(iniString, file, createParentDir);
5✔
1339
  }
1✔
1340

1341
  @Override
1342
  public Duration getFileAge(Path path) {
1343
    if (Files.exists(path)) {
5✔
1344
      try {
1345
        long currentTime = System.currentTimeMillis();
2✔
1346
        long fileModifiedTime = Files.getLastModifiedTime(path).toMillis();
6✔
1347
        return Duration.ofMillis(currentTime - fileModifiedTime);
5✔
1348
      } catch (IOException e) {
×
1349
        this.context.warning().log(e, "Could not get modification-time of {}.", path);
×
1350
      }
×
1351
    } else {
1352
      this.context.debug("Path {} is missing - skipping modification-time and file age check.", path);
10✔
1353
    }
1354
    return null;
2✔
1355
  }
1356

1357
  @Override
1358
  public boolean isFileAgeRecent(Path path, Duration cacheDuration) {
1359

1360
    Duration age = getFileAge(path);
4✔
1361
    if (age == null) {
2✔
1362
      return false;
2✔
1363
    }
1364
    context.debug("The path {} was last updated {} ago and caching duration is {}.", path, age, cacheDuration);
18✔
1365
    return (age.toMillis() <= cacheDuration.toMillis());
10✔
1366
  }
1367
}
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