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

devonfw / IDEasy / 17798378835

17 Sep 2025 12:58PM UTC coverage: 68.618% (-0.04%) from 68.656%
17798378835

push

github

web-flow
#1490: fix linking folders as junction with absolute path on Windows as fallback (#1494)

3418 of 5447 branches covered (62.75%)

Branch coverage included in aggregate %.

8914 of 12525 relevant lines covered (71.17%)

3.13 hits per line

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

66.12
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.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.ArchiveOutputStream;
50
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
51
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
52
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
53
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
54
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;
55
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
56
import org.apache.commons.io.IOUtils;
57

58
import com.devonfw.tools.ide.cli.CliException;
59
import com.devonfw.tools.ide.cli.CliOfflineException;
60
import com.devonfw.tools.ide.context.IdeContext;
61
import com.devonfw.tools.ide.io.ini.IniComment;
62
import com.devonfw.tools.ide.io.ini.IniFile;
63
import com.devonfw.tools.ide.io.ini.IniSection;
64
import com.devonfw.tools.ide.os.SystemInfoImpl;
65
import com.devonfw.tools.ide.process.ProcessContext;
66
import com.devonfw.tools.ide.process.ProcessMode;
67
import com.devonfw.tools.ide.process.ProcessResult;
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
  @Override
305
  public boolean isJunction(Path path) {
306

307
    if (!SystemInfoImpl.INSTANCE.isWindows()) {
3!
308
      return false;
2✔
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
   */
443
  private void deleteLinkIfExists(Path path) {
444

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

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

450
    if (isJunction || isSymlink) {
4!
451
      this.context.info("Deleting previous " + (isJunction ? "junction" : "symlink") + " at " + path);
9!
452
      try {
453
        Files.delete(path);
2✔
454
      } catch (IOException e) {
×
455
        throw new IllegalStateException("Failed to delete link at " + path, e);
×
456
      }
1✔
457
    }
458
  }
1✔
459

460
  /**
461
   * Adapts the given {@link Path} to be relative or absolute depending on the given {@code relative} flag. Additionally, {@link Path#toRealPath(LinkOption...)}
462
   * is applied to {@code target}.
463
   *
464
   * @param target the {@link Path} the link should point to and that is to be adapted.
465
   * @param link the {@link Path} to the link. It is used to calculate the relative path to the {@code target} if {@code relative} is set to {@code true}.
466
   * @param relative the {@code relative} flag.
467
   * @return the adapted {@link Path}.
468
   * @see #symlink(Path, Path, boolean)
469
   */
470
  private Path adaptPath(Path target, Path link, boolean relative) {
471

472
    if (!target.isAbsolute()) {
3✔
473
      target = link.resolveSibling(target);
4✔
474
    }
475
    try {
476
      target = target.toRealPath(LinkOption.NOFOLLOW_LINKS); // to transform ../d1/../d2 to ../d2
9✔
477
    } catch (IOException e) {
×
478
      throw new RuntimeException("Failed to get real path of " + target, e);
×
479
    }
1✔
480
    if (relative) {
2✔
481
      target = link.getParent().relativize(target);
5✔
482
      // to make relative links like this work: dir/link -> dir
483
      target = (target.toString().isEmpty()) ? Path.of(".") : target;
11✔
484
    }
485
    return target;
2✔
486
  }
487

488
  /**
489
   * Creates a Windows link using mklink at {@code link} pointing to {@code target}.
490
   *
491
   * @param target the {@link Path} the link will point to.
492
   * @param link the {@link Path} where to create the link.
493
   * @param type the {@link PathLinkType}.
494
   */
495
  private void mklinkOnWindows(Path target, Path link, PathLinkType type) {
496

497
    this.context.trace("Creating a Windows link at {} pointing to {}", link, target);
×
498
    ProcessContext pc = this.context.newProcess().executable("cmd")
×
499
        .addArgs("/c", "mklink", type.getMklinkOption());
×
500
    if (type == PathLinkType.SYMBOLIC_LINK && Files.isDirectory(target)) {
×
501
      pc.addArg("/j");
×
502
      target = target.toAbsolutePath();
×
503
    }
504
    pc = pc.addArgs(link.toString(), target.toString());
×
505
    ProcessResult result = pc
×
506
        .run(ProcessMode.DEFAULT);
×
507
    result.failOnError();
×
508
  }
×
509

510
  @Override
511
  public void link(Path target, Path link, boolean relative, PathLinkType type) {
512

513
    final Path finalTarget;
514
    try {
515
      finalTarget = adaptPath(target, link, relative);
6✔
516
    } catch (Exception e) {
×
517
      throw new IllegalStateException("Failed to adapt target (" + target + ") for link (" + link + ") and relative (" + relative + ")", e);
×
518
    }
1✔
519
    String relativeOrAbsolute = finalTarget.isAbsolute() ? "absolute" : "relative";
7✔
520
    this.context.debug("Creating {} {} at {} pointing to {}", relativeOrAbsolute, type, link, finalTarget);
22✔
521
    deleteLinkIfExists(link);
3✔
522
    try {
523
      if (type == PathLinkType.SYMBOLIC_LINK) {
3!
524
        Files.createSymbolicLink(link, finalTarget);
7✔
525
      } else if (type == PathLinkType.HARD_LINK) {
×
526
        Files.createLink(link, finalTarget);
×
527
      } else {
528
        throw new IllegalStateException("" + type);
×
529
      }
530
    } catch (FileSystemException e) {
×
531
      if (SystemInfoImpl.INSTANCE.isWindows()) {
×
532
        this.context.info(
×
533
            "Due to lack of permissions, Microsoft's mklink with junction had to be used to create a Symlink. See\n"
534
                + "https://github.com/devonfw/IDEasy/blob/main/documentation/symlink.adoc for further details. Error was: "
535
                + e.getMessage());
×
536
        mklinkOnWindows(finalTarget, link, type);
×
537
      } else {
538
        throw new RuntimeException(e);
×
539
      }
540
    } catch (IOException e) {
×
541
      throw new IllegalStateException(
×
542
          "Failed to create a " + relativeOrAbsolute + " " + type + " at " + link + " pointing to " + target, e);
543
    }
1✔
544
  }
1✔
545

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

741
    this.context.info("Extracting TAR file {} to {}", file, targetDir);
14✔
742

743
    final List<PathLink> links = new ArrayList<>();
4✔
744
    try (InputStream is = Files.newInputStream(file);
5✔
745
        ArchiveInputStream<?> ais = unpacker.apply(is);
5✔
746
        IdeProgressBar pb = this.context.newProgressbarForExtracting(getFileSize(file))) {
7✔
747

748
      final boolean isTar = (ais instanceof TarArchiveInputStream);
3✔
749
      final boolean isWindows = this.context.getSystemInfo().isWindows();
5✔
750
      final Path root = targetDir.toAbsolutePath().normalize();
4✔
751

752
      ArchiveEntry entry = ais.getNextEntry();
3✔
753
      while (entry != null) {
2✔
754
        String entryName = entry.getName();
3✔
755
        Path entryPath = resolveRelativePathSecure(entryName, root);
5✔
756
        PathPermissions permissions = null;
2✔
757
        PathLinkType linkType = null;
2✔
758
        if (entry instanceof TarArchiveEntry tae) {
6!
759
          if (tae.isSymbolicLink()) {
3!
760
            linkType = PathLinkType.SYMBOLIC_LINK;
×
761
          } else if (tae.isLink()) {
3!
762
            linkType = PathLinkType.HARD_LINK;
×
763
          }
764
          if (linkType == null) {
2!
765
            permissions = PathPermissions.of(tae.getMode());
5✔
766
          } else {
767
            Path parent = entryPath.getParent();
×
768
            String linkName = tae.getLinkName();
×
769
            Path linkTarget = parent.resolve(linkName).normalize();
×
770
            Path target = resolveRelativePathSecure(linkTarget, root, linkName);
×
771
            links.add(new PathLink(entryPath, target, linkType));
×
772
            mkdirs(parent);
×
773
          }
774
        }
775
        if (entry.isDirectory()) {
3✔
776
          mkdirs(entryPath);
4✔
777
        } else if (linkType == null) { // regular file
2!
778
          mkdirs(entryPath.getParent());
4✔
779
          Files.copy(ais, entryPath, StandardCopyOption.REPLACE_EXISTING);
10✔
780
          // POSIX perms on non-Windows
781
          if (!isWindows && (permissions != null)) {
4!
782
            setFilePermissions(entryPath, permissions, false);
5✔
783
          }
784
        }
785
        pb.stepBy(Math.max(0L, entry.getSize()));
6✔
786
        entry = ais.getNextEntry();
3✔
787
      }
1✔
788
      // post process links
789
      for (PathLink link : links) {
6!
790
        link(link);
×
791
      }
×
792
    } catch (Exception e) {
×
793
      throw new IllegalStateException("Failed to extract " + file + " to " + targetDir, e);
×
794
    }
1✔
795
  }
1✔
796

797
  private Path resolveRelativePathSecure(String entryName, Path root) {
798

799
    Path entryPath = root.resolve(entryName).normalize();
5✔
800
    return resolveRelativePathSecure(entryPath, root, entryName);
6✔
801
  }
802

803
  private Path resolveRelativePathSecure(Path entryPath, Path root, String entryName) {
804

805
    if (!entryPath.startsWith(root)) {
4!
806
      throw new IllegalStateException("Preventing path traversal attack from " + entryName + " to " + entryPath + " leaving " + root);
×
807
    }
808
    return entryPath;
2✔
809
  }
810

811

812
  @Override
813
  public void extractDmg(Path file, Path targetDir) {
814

815
    this.context.info("Extracting DMG file {} to {}", file, targetDir);
×
816
    assert this.context.getSystemInfo().isMac();
×
817

818
    Path mountPath = this.context.getIdeHome().resolve(IdeContext.FOLDER_UPDATES).resolve(IdeContext.FOLDER_VOLUME);
×
819
    mkdirs(mountPath);
×
820
    ProcessContext pc = this.context.newProcess();
×
821
    pc.executable("hdiutil");
×
822
    pc.addArgs("attach", "-quiet", "-nobrowse", "-mountpoint", mountPath, file);
×
823
    pc.run();
×
824
    Path appPath = findFirst(mountPath, p -> p.getFileName().toString().endsWith(".app"), false);
×
825
    if (appPath == null) {
×
826
      throw new IllegalStateException("Failed to unpack DMG as no MacOS *.app was found in file " + file);
×
827
    }
828

829
    copy(appPath, targetDir, FileCopyMode.COPY_TREE_OVERRIDE_TREE);
×
830
    pc.addArgs("detach", "-force", mountPath);
×
831
    pc.run();
×
832
  }
×
833

834
  @Override
835
  public void extractMsi(Path file, Path targetDir) {
836

837
    this.context.info("Extracting MSI file {} to {}", file, targetDir);
×
838
    this.context.newProcess().executable("msiexec").addArgs("/a", file, "/qn", "TARGETDIR=" + targetDir).run();
×
839
    // msiexec also creates a copy of the MSI
840
    Path msiCopy = targetDir.resolve(file.getFileName());
×
841
    delete(msiCopy);
×
842
  }
×
843

844
  @Override
845
  public void extractPkg(Path file, Path targetDir) {
846

847
    this.context.info("Extracting PKG file {} to {}", file, targetDir);
×
848
    Path tmpDirPkg = createTempDir("ide-pkg-");
×
849
    ProcessContext pc = this.context.newProcess();
×
850
    // we might also be able to use cpio from commons-compression instead of external xar...
851
    pc.executable("xar").addArgs("-C", tmpDirPkg, "-xf", file).run();
×
852
    Path contentPath = findFirst(tmpDirPkg, p -> p.getFileName().toString().equals("Payload"), true);
×
853
    extractTar(contentPath, targetDir, TarCompression.GZ);
×
854
    delete(tmpDirPkg);
×
855
  }
×
856

857
  @Override
858
  public void compress(Path dir, OutputStream out, String format) {
859

860
    String extension = FilenameUtil.getExtension(format);
3✔
861
    TarCompression tarCompression = TarCompression.of(extension);
3✔
862
    if (tarCompression != null) {
2!
863
      compressTar(dir, out, tarCompression);
6✔
864
    } else if (extension.equals("zip")) {
×
865
      compressZip(dir, out);
×
866
    } else {
867
      throw new IllegalArgumentException("Unsupported extension: " + extension);
×
868
    }
869
  }
1✔
870

871
  @Override
872
  public void compressTar(Path dir, OutputStream out, TarCompression tarCompression) {
873
    switch (tarCompression) {
8!
874
      case null -> compressTar(dir, out);
×
875
      case NONE -> compressTar(dir, out);
×
876
      case GZ -> compressTarGz(dir, out);
5✔
877
      case BZIP2 -> compressTarBzip2(dir, out);
×
878
      default -> throw new IllegalArgumentException("Unsupported tar compression: " + tarCompression);
×
879
    }
880
  }
1✔
881

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

891
  @Override
892
  public void compressTarBzip2(Path dir, OutputStream out) {
893
    try (BZip2CompressorOutputStream bzip2Out = new BZip2CompressorOutputStream(out)) {
×
894
      compressTarOrThrow(dir, bzip2Out);
×
895
    } catch (IOException e) {
×
896
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar.bz2 file.", e);
×
897
    }
×
898
  }
×
899

900
  @Override
901
  public void compressTar(Path dir, OutputStream out) {
902
    try {
903
      compressTarOrThrow(dir, out);
×
904
    } catch (IOException e) {
×
905
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar file.", e);
×
906
    }
×
907
  }
×
908

909
  private void compressTarOrThrow(Path dir, OutputStream out) throws IOException {
910
    try (TarArchiveOutputStream tarOut = new TarArchiveOutputStream(out)) {
5✔
911
      compressRecursive(dir, tarOut, "");
5✔
912
      tarOut.finish();
2✔
913
    }
914
  }
1✔
915

916
  @Override
917
  public void compressZip(Path dir, OutputStream out) {
918
    try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(out)) {
×
919
      compressRecursive(dir, zipOut, "");
×
920
      zipOut.finish();
×
921
    } catch (IOException e) {
×
922
      throw new IllegalStateException("Failed to compress directory " + dir + " to zip file.", e);
×
923
    }
×
924
  }
×
925

926
  private <E extends ArchiveEntry> void compressRecursive(Path path, ArchiveOutputStream<E> out, String relativePath) {
927
    try (Stream<Path> childStream = Files.list(path)) {
3✔
928
      Iterator<Path> iterator = childStream.iterator();
3✔
929
      while (iterator.hasNext()) {
3✔
930
        Path child = iterator.next();
4✔
931
        String relativeChildPath = relativePath + "/" + child.getFileName().toString();
6✔
932
        boolean isDirectory = Files.isDirectory(child);
5✔
933
        E archiveEntry = out.createArchiveEntry(child, relativeChildPath);
7✔
934
        if (archiveEntry instanceof TarArchiveEntry tarEntry) {
6!
935
          FileTime none = FileTime.fromMillis(0);
3✔
936
          tarEntry.setCreationTime(none);
3✔
937
          tarEntry.setModTime(none);
3✔
938
          tarEntry.setLastAccessTime(none);
3✔
939
          tarEntry.setLastModifiedTime(none);
3✔
940
          tarEntry.setUserId(0);
3✔
941
          tarEntry.setUserName("user");
3✔
942
          tarEntry.setGroupId(0);
3✔
943
          tarEntry.setGroupName("group");
3✔
944
          if (isDirectory) {
2✔
945
            tarEntry.setMode(MODE_RWX_RX_RX);
4✔
946
          } else {
947
            if (relativePath.endsWith("bin")) {
4✔
948
              tarEntry.setMode(MODE_RWX_RX_RX);
4✔
949
            } else {
950
              tarEntry.setMode(MODE_RW_R_R);
3✔
951
            }
952
          }
953
        }
954
        out.putArchiveEntry(archiveEntry);
3✔
955
        if (!isDirectory) {
2✔
956
          try (InputStream in = Files.newInputStream(child)) {
5✔
957
            IOUtils.copy(in, out);
4✔
958
          }
959
        }
960
        out.closeArchiveEntry();
2✔
961
        if (isDirectory) {
2✔
962
          compressRecursive(child, out, relativeChildPath);
5✔
963
        }
964
      }
1✔
965
    } catch (IOException e) {
×
966
      throw new IllegalStateException("Failed to compress " + path, e);
×
967
    }
1✔
968
  }
1✔
969

970
  @Override
971
  public void delete(Path path) {
972

973
    if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
9✔
974
      this.context.trace("Deleting {} skipped as the path does not exist.", path);
10✔
975
      return;
1✔
976
    }
977
    this.context.debug("Deleting {} ...", path);
10✔
978
    try {
979
      if (Files.isSymbolicLink(path) || isJunction(path)) {
7!
980
        Files.delete(path);
3✔
981
      } else {
982
        deleteRecursive(path);
3✔
983
      }
984
    } catch (IOException e) {
×
985
      throw new IllegalStateException("Failed to delete " + path, e);
×
986
    }
1✔
987
  }
1✔
988

989
  private void deleteRecursive(Path path) throws IOException {
990

991
    if (Files.isDirectory(path)) {
5✔
992
      try (Stream<Path> childStream = Files.list(path)) {
3✔
993
        Iterator<Path> iterator = childStream.iterator();
3✔
994
        while (iterator.hasNext()) {
3✔
995
          Path child = iterator.next();
4✔
996
          deleteRecursive(child);
3✔
997
        }
1✔
998
      }
999
    }
1000
    this.context.trace("Deleting {} ...", path);
10✔
1001
    boolean isSetWritable = setWritable(path, true);
5✔
1002
    if (!isSetWritable) {
2✔
1003
      this.context.debug("Couldn't give write access to file: " + path);
6✔
1004
    }
1005
    Files.delete(path);
2✔
1006
  }
1✔
1007

1008
  @Override
1009
  public Path findFirst(Path dir, Predicate<Path> filter, boolean recursive) {
1010

1011
    try {
1012
      if (!Files.isDirectory(dir)) {
5✔
1013
        return null;
2✔
1014
      }
1015
      return findFirstRecursive(dir, filter, recursive);
6✔
1016
    } catch (IOException e) {
×
1017
      throw new IllegalStateException("Failed to search for file in " + dir, e);
×
1018
    }
1019
  }
1020

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

1023
    List<Path> folders = null;
2✔
1024
    try (Stream<Path> childStream = Files.list(dir)) {
3✔
1025
      Iterator<Path> iterator = childStream.iterator();
3✔
1026
      while (iterator.hasNext()) {
3✔
1027
        Path child = iterator.next();
4✔
1028
        if (filter.test(child)) {
4✔
1029
          return child;
4✔
1030
        } else if (recursive && Files.isDirectory(child)) {
2!
1031
          if (folders == null) {
×
1032
            folders = new ArrayList<>();
×
1033
          }
1034
          folders.add(child);
×
1035
        }
1036
      }
1✔
1037
    }
4!
1038
    if (folders != null) {
2!
1039
      for (Path child : folders) {
×
1040
        Path match = findFirstRecursive(child, filter, recursive);
×
1041
        if (match != null) {
×
1042
          return match;
×
1043
        }
1044
      }
×
1045
    }
1046
    return null;
2✔
1047
  }
1048

1049
  @Override
1050
  public List<Path> listChildrenMapped(Path dir, Function<Path, Path> filter) {
1051

1052
    if (!Files.isDirectory(dir)) {
5✔
1053
      return List.of();
2✔
1054
    }
1055
    List<Path> children = new ArrayList<>();
4✔
1056
    try (Stream<Path> childStream = Files.list(dir)) {
3✔
1057
      Iterator<Path> iterator = childStream.iterator();
3✔
1058
      while (iterator.hasNext()) {
3✔
1059
        Path child = iterator.next();
4✔
1060
        Path filteredChild = filter.apply(child);
5✔
1061
        if (filteredChild != null) {
2✔
1062
          if (filteredChild == child) {
3!
1063
            this.context.trace("Accepted file {}", child);
11✔
1064
          } else {
1065
            this.context.trace("Accepted file {} and mapped to {}", child, filteredChild);
×
1066
          }
1067
          children.add(filteredChild);
5✔
1068
        } else {
1069
          this.context.trace("Ignoring file {} according to filter", child);
10✔
1070
        }
1071
      }
1✔
1072
    } catch (IOException e) {
×
1073
      throw new IllegalStateException("Failed to find children of directory " + dir, e);
×
1074
    }
1✔
1075
    return children;
2✔
1076
  }
1077

1078
  @Override
1079
  public boolean isEmptyDir(Path dir) {
1080

1081
    return listChildren(dir, f -> true).isEmpty();
8✔
1082
  }
1083

1084
  private long getFileSize(Path file) {
1085

1086
    try {
1087
      return Files.size(file);
3✔
1088
    } catch (IOException e) {
×
1089
      this.context.warning(e.getMessage(), e);
×
1090
      return 0;
×
1091
    }
1092
  }
1093

1094
  private long getFileSizeRecursive(Path path) {
1095

1096
    long size = 0;
2✔
1097
    if (Files.isDirectory(path)) {
5✔
1098
      try (Stream<Path> childStream = Files.list(path)) {
3✔
1099
        Iterator<Path> iterator = childStream.iterator();
3✔
1100
        while (iterator.hasNext()) {
3✔
1101
          Path child = iterator.next();
4✔
1102
          size += getFileSizeRecursive(child);
6✔
1103
        }
1✔
1104
      } catch (IOException e) {
×
1105
        throw new RuntimeException("Failed to iterate children of folder " + path, e);
×
1106
      }
1✔
1107
    } else {
1108
      size += getFileSize(path);
6✔
1109
    }
1110
    return size;
2✔
1111
  }
1112

1113
  @Override
1114
  public Path findExistingFile(String fileName, List<Path> searchDirs) {
1115

1116
    for (Path dir : searchDirs) {
10!
1117
      Path filePath = dir.resolve(fileName);
4✔
1118
      try {
1119
        if (Files.exists(filePath)) {
5✔
1120
          return filePath;
2✔
1121
        }
1122
      } catch (Exception e) {
×
1123
        throw new IllegalStateException("Unexpected error while checking existence of file " + filePath + " .", e);
×
1124
      }
1✔
1125
    }
1✔
1126
    return null;
×
1127
  }
1128

1129
  @Override
1130
  public boolean setWritable(Path file, boolean writable) {
1131
    try {
1132
      // POSIX
1133
      PosixFileAttributeView posix = Files.getFileAttributeView(file, PosixFileAttributeView.class);
7✔
1134
      if (posix != null) {
2!
1135
        Set<PosixFilePermission> permissions = new HashSet<>(posix.readAttributes().permissions());
7✔
1136
        boolean changed;
1137
        if (writable) {
2!
1138
          changed = permissions.add(PosixFilePermission.OWNER_WRITE);
5✔
1139
        } else {
1140
          changed = permissions.remove(PosixFilePermission.OWNER_WRITE);
×
1141
        }
1142
        if (changed) {
2!
1143
          posix.setPermissions(permissions);
×
1144
        }
1145
        return true;
2✔
1146
      }
1147

1148
      // Windows
1149
      DosFileAttributeView dos = Files.getFileAttributeView(file, DosFileAttributeView.class);
×
1150
      if (dos != null) {
×
1151
        dos.setReadOnly(!writable);
×
1152
        return true;
×
1153
      }
1154

1155
      this.context.debug("Failed to set writing permission for file {}", file);
×
1156
      return false;
×
1157

1158
    } catch (IOException e) {
1✔
1159
      this.context.debug("Error occurred when trying to set writing permission for file " + file + ": " + e);
8✔
1160
      return false;
2✔
1161
    }
1162
  }
1163

1164
  @Override
1165
  public void makeExecutable(Path path, boolean confirm) {
1166

1167
    if (Files.exists(path)) {
5✔
1168
      if (skipPermissionsIfWindows(path)) {
4!
1169
        return;
×
1170
      }
1171
      Set<PosixFilePermission> existingPosixPermissions;
1172
      try {
1173
        // Read the current file permissions
1174
        existingPosixPermissions = Files.getPosixFilePermissions(path);
5✔
1175
      } catch (IOException e) {
×
1176
        throw new RuntimeException("Failed to get permissions for " + path, e);
×
1177
      }
1✔
1178

1179
      PathPermissions existingPermissions = PathPermissions.of(existingPosixPermissions);
3✔
1180
      PathPermissions executablePermissions = existingPermissions.makeExecutable();
3✔
1181
      boolean update = (executablePermissions != existingPermissions);
7✔
1182
      if (update) {
2✔
1183
        if (confirm) {
2!
1184
          boolean yesContinue = this.context.question(
×
1185
              "We want to execute {} but this command seems to lack executable permissions!\n"
1186
                  + "Most probably the tool vendor did forgot to add x-flags in the binary release package.\n"
1187
                  + "Before running the command, we suggest to set executable permissions to the file:\n"
1188
                  + "{}\n"
1189
                  + "For security reasons we ask for your confirmation so please check this request.\n"
1190
                  + "Changing permissions from {} to {}.\n"
1191
                  + "Do you confirm to make the command executable before running it?", path.getFileName(), path, existingPermissions, executablePermissions);
×
1192
          if (!yesContinue) {
×
1193
            return;
×
1194
          }
1195
        }
1196
        setFilePermissions(path, executablePermissions, false);
6✔
1197
      } else {
1198
        this.context.trace("Executable flags already present so no need to set them for file {}", path);
10✔
1199
      }
1200
    } else {
1✔
1201
      this.context.warning("Cannot set executable flag on file that does not exist: {}", path);
10✔
1202
    }
1203
  }
1✔
1204

1205
  @Override
1206
  public void setFilePermissions(Path path, PathPermissions permissions, boolean logErrorAndContinue) {
1207

1208
    if (skipPermissionsIfWindows(path)) {
4!
1209
      return;
×
1210
    }
1211
    try {
1212
      this.context.debug("Setting permissions for {} to {}", path, permissions);
14✔
1213
      // Set the new permissions
1214
      Files.setPosixFilePermissions(path, permissions.toPosix());
5✔
1215
    } catch (IOException e) {
×
1216
      if (logErrorAndContinue) {
×
1217
        this.context.warning().log(e, "Failed to set permissions to {} for path {}", permissions, path);
×
1218
      } else {
1219
        throw new RuntimeException("Failed to set permissions to " + permissions + " for path " + path, e);
×
1220
      }
1221
    }
1✔
1222
  }
1✔
1223

1224
  private boolean skipPermissionsIfWindows(Path path) {
1225
    if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
1226
      this.context.trace("Windows does not have file permissions hence omitting for {}", path);
×
1227
      return true;
×
1228
    }
1229
    return false;
2✔
1230
  }
1231

1232
  @Override
1233
  public void touch(Path file) {
1234

1235
    if (Files.exists(file)) {
5✔
1236
      try {
1237
        Files.setLastModifiedTime(file, FileTime.fromMillis(System.currentTimeMillis()));
5✔
1238
      } catch (IOException e) {
×
1239
        throw new IllegalStateException("Could not update modification-time of " + file, e);
×
1240
      }
1✔
1241
    } else {
1242
      try {
1243
        Files.createFile(file);
5✔
1244
      } catch (IOException e) {
1✔
1245
        throw new IllegalStateException("Could not create empty file " + file, e);
8✔
1246
      }
1✔
1247
    }
1248
  }
1✔
1249

1250
  @Override
1251
  public String readFileContent(Path file) {
1252

1253
    this.context.trace("Reading content of file from {}", file);
10✔
1254
    if (!Files.exists((file))) {
5!
1255
      this.context.debug("File {} does not exist", file);
×
1256
      return null;
×
1257
    }
1258
    try {
1259
      String content = Files.readString(file);
3✔
1260
      this.context.trace("Completed reading {} character(s) from file {}", content.length(), 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 writeFileContent(String content, Path file, boolean createParentDir) {
1269

1270
    if (createParentDir) {
2✔
1271
      mkdirs(file.getParent());
4✔
1272
    }
1273
    if (content == null) {
2!
1274
      content = "";
×
1275
    }
1276
    this.context.trace("Writing content with {} character(s) to file {}", content.length(), file);
16✔
1277
    if (Files.exists(file)) {
5✔
1278
      this.context.info("Overriding content of file {}", file);
10✔
1279
    }
1280
    try {
1281
      Files.writeString(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 List<String> readFileLines(Path file) {
1290

1291
    this.context.trace("Reading content of file from {}", file);
10✔
1292
    if (!Files.exists(file)) {
5✔
1293
      this.context.warning("File {} does not exist", file);
10✔
1294
      return null;
2✔
1295
    }
1296
    try {
1297
      List<String> content = Files.readAllLines(file);
3✔
1298
      this.context.trace("Completed reading {} lines from file {}", content.size(), file);
16✔
1299
      return content;
2✔
1300
    } catch (IOException e) {
×
1301
      throw new IllegalStateException("Failed to read file " + file, e);
×
1302
    }
1303
  }
1304

1305
  @Override
1306
  public void writeFileLines(List<String> content, Path file, boolean createParentDir) {
1307

1308
    if (createParentDir) {
2!
1309
      mkdirs(file.getParent());
×
1310
    }
1311
    if (content == null) {
2!
1312
      content = List.of();
×
1313
    }
1314
    this.context.trace("Writing content with {} lines to file {}", content.size(), file);
16✔
1315
    if (Files.exists(file)) {
5✔
1316
      this.context.debug("Overriding content of file {}", file);
10✔
1317
    }
1318
    try {
1319
      Files.write(file, content);
6✔
1320
      this.context.trace("Wrote content to file {}", file);
10✔
1321
    } catch (IOException e) {
×
1322
      throw new RuntimeException("Failed to write file " + file, e);
×
1323
    }
1✔
1324
  }
1✔
1325

1326
  @Override
1327
  public void readProperties(Path file, Properties properties) {
1328

1329
    try (Reader reader = Files.newBufferedReader(file)) {
3✔
1330
      properties.load(reader);
3✔
1331
      this.context.debug("Successfully loaded {} properties from {}", properties.size(), file);
16✔
1332
    } catch (IOException e) {
×
1333
      throw new IllegalStateException("Failed to read properties file: " + file, e);
×
1334
    }
1✔
1335
  }
1✔
1336

1337
  @Override
1338
  public void writeProperties(Properties properties, Path file, boolean createParentDir) {
1339

1340
    if (createParentDir) {
2✔
1341
      mkdirs(file.getParent());
4✔
1342
    }
1343
    try (Writer writer = Files.newBufferedWriter(file)) {
5✔
1344
      properties.store(writer, null); // do not get confused - Java still writes a date/time header that cannot be omitted
4✔
1345
      this.context.debug("Successfully saved {} properties to {}", properties.size(), file);
16✔
1346
    } catch (IOException e) {
×
1347
      throw new IllegalStateException("Failed to save properties file during tests.", e);
×
1348
    }
1✔
1349
  }
1✔
1350

1351
  @Override
1352
  public void readIniFile(Path file, IniFile iniFile) {
1353
    if (!Files.exists(file)) {
5!
1354
      this.context.debug("INI file {} does not exist.", iniFile);
×
1355
      return;
×
1356
    }
1357
    List<String> iniLines = readFileLines(file);
4✔
1358
    IniSection currentIniSection = iniFile.getInitialSection();
3✔
1359
    for (String line : iniLines) {
10✔
1360
      if (line.trim().startsWith("[")) {
5✔
1361
        currentIniSection = iniFile.getOrCreateSection(line);
5✔
1362
      } else if (line.isBlank() || IniComment.COMMENT_SYMBOLS.contains(line.trim().charAt(0))) {
11✔
1363
        currentIniSection.addComment(line);
4✔
1364
      } else {
1365
        int index = line.indexOf('=');
4✔
1366
        if (index > 0) {
2!
1367
          currentIniSection.setProperty(line);
3✔
1368
        }
1369
      }
1370
    }
1✔
1371
  }
1✔
1372

1373
  @Override
1374
  public void writeIniFile(IniFile iniFile, Path file, boolean createParentDir) {
1375
    String iniString = iniFile.toString();
3✔
1376
    writeFileContent(iniString, file, createParentDir);
5✔
1377
  }
1✔
1378

1379
  @Override
1380
  public Duration getFileAge(Path path) {
1381
    if (Files.exists(path)) {
5✔
1382
      try {
1383
        long currentTime = System.currentTimeMillis();
2✔
1384
        long fileModifiedTime = Files.getLastModifiedTime(path).toMillis();
6✔
1385
        return Duration.ofMillis(currentTime - fileModifiedTime);
5✔
1386
      } catch (IOException e) {
×
1387
        this.context.warning().log(e, "Could not get modification-time of {}.", path);
×
1388
      }
×
1389
    } else {
1390
      this.context.debug("Path {} is missing - skipping modification-time and file age check.", path);
10✔
1391
    }
1392
    return null;
2✔
1393
  }
1394

1395
  @Override
1396
  public boolean isFileAgeRecent(Path path, Duration cacheDuration) {
1397

1398
    Duration age = getFileAge(path);
4✔
1399
    if (age == null) {
2✔
1400
      return false;
2✔
1401
    }
1402
    context.debug("The path {} was last updated {} ago and caching duration is {}.", path, age, cacheDuration);
18✔
1403
    return (age.toMillis() <= cacheDuration.toMillis());
10✔
1404
  }
1405
}
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