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

devonfw / IDEasy / 17854514596

19 Sep 2025 09:34AM UTC coverage: 68.475% (-0.06%) from 68.539%
17854514596

push

github

web-flow
#907: add NpmRepository and further node/npm support as preparation for yarn and corepack (#1499)

Co-authored-by: jan-vcapgemini <59438728+jan-vcapgemini@users.noreply.github.com>

3431 of 5487 branches covered (62.53%)

Branch coverage included in aggregate %.

8978 of 12635 relevant lines covered (71.06%)

3.12 hits per line

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

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

43
import org.apache.commons.compress.archivers.ArchiveEntry;
44
import org.apache.commons.compress.archivers.ArchiveInputStream;
45
import org.apache.commons.compress.archivers.ArchiveOutputStream;
46
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
47
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
48
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
49
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
50
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;
51
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
52
import org.apache.commons.io.IOUtils;
53

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

69
/**
70
 * Implementation of {@link FileAccess}.
71
 */
72
public class FileAccessImpl extends HttpDownloader implements FileAccess {
73

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

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

80
  private static final int MODE_RWX_RX_RX = 0755;
81
  private static final int MODE_RW_R_R = 0644;
82

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

85
  private final IdeContext context;
86

87
  /**
88
   * The constructor.
89
   *
90
   * @param context the {@link IdeContext} to use.
91
   */
92
  public FileAccessImpl(IdeContext context) {
93

94
    super();
2✔
95
    this.context = context;
3✔
96
  }
1✔
97

98
  @Override
99
  public void download(String url, Path target) {
100

101
    if (this.context.isOffline()) {
4!
102
      throw CliOfflineException.ofDownloadViaUrl(url);
×
103
    }
104
    if (url.startsWith("http")) {
4✔
105
      downloadViaHttp(url, target);
5✔
106
    } else if (url.startsWith("ftp") || url.startsWith("sftp")) {
8!
107
      throw new IllegalArgumentException("Unsupported download URL: " + url);
×
108
    } else {
109
      Path source = Path.of(url);
5✔
110
      if (isFile(source)) {
4!
111
        // network drive
112
        copyFileWithProgressBar(source, target);
5✔
113
      } else {
114
        throw new IllegalArgumentException("Download path does not point to a downloadable file: " + url);
×
115
      }
116
    }
117
  }
1✔
118

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

142
  private void downloadWithHttpVersion(String url, Path target, Version httpVersion) throws Exception {
143

144
    if (httpVersion == null) {
2!
145
      this.context.info("Trying to download {} from {}", target.getFileName(), url);
16✔
146
    } else {
147
      this.context.info("Trying to download: {} with HTTP protocol version: {}", url, httpVersion);
×
148
    }
149
    mkdirs(target.getParent());
4✔
150
    httpGet(url, httpVersion, (response) -> downloadFileWithProgressBar(url, target, response));
13✔
151
  }
1✔
152

153
  /**
154
   * Downloads a file while showing a {@link IdeProgressBar}.
155
   *
156
   * @param url the url to download.
157
   * @param target Path of the target directory.
158
   * @param response the {@link HttpResponse} to use.
159
   */
160
  private void downloadFileWithProgressBar(String url, Path target, HttpResponse<InputStream> response) {
161

162
    long contentLength = response.headers().firstValueAsLong("content-length").orElse(-1);
7✔
163
    if (contentLength < 0) {
4✔
164
      this.context.warning("Content-Length was not provided by download from {}", url);
10✔
165
    }
166

167
    byte[] data = new byte[1024];
3✔
168
    boolean fileComplete = false;
2✔
169
    int count;
170

171
    try (InputStream body = response.body();
4✔
172
        FileOutputStream fileOutput = new FileOutputStream(target.toFile());
6✔
173
        BufferedOutputStream bufferedOut = new BufferedOutputStream(fileOutput, data.length);
7✔
174
        IdeProgressBar pb = this.context.newProgressBarForDownload(contentLength)) {
5✔
175
      while (!fileComplete) {
2✔
176
        count = body.read(data);
4✔
177
        if (count <= 0) {
2✔
178
          fileComplete = true;
3✔
179
        } else {
180
          bufferedOut.write(data, 0, count);
5✔
181
          pb.stepBy(count);
5✔
182
        }
183
      }
184
    } catch (Exception e) {
×
185
      throw new RuntimeException(e);
×
186
    }
1✔
187
  }
1✔
188

189
  private void copyFileWithProgressBar(Path source, Path target) {
190

191
    long size = getFileSize(source);
4✔
192
    if (size < 100_000) {
4✔
193
      copy(source, target, FileCopyMode.COPY_FILE_TO_TARGET_OVERRIDE);
5✔
194
      return;
1✔
195
    }
196
    try (InputStream in = Files.newInputStream(source);
5✔
197
        OutputStream out = Files.newOutputStream(target)) {
5✔
198
      byte[] buf = new byte[1024];
3✔
199
      try (IdeProgressBar pb = this.context.newProgressbarForCopying(size)) {
5✔
200
        int readBytes;
201
        while ((readBytes = in.read(buf)) > 0) {
6✔
202
          out.write(buf, 0, readBytes);
5✔
203
          pb.stepBy(readBytes);
5✔
204
        }
205
      } catch (Exception e) {
×
206
        throw new RuntimeException(e);
×
207
      }
1✔
208
    } catch (IOException e) {
×
209
      throw new RuntimeException("Failed to copy from " + source + " to " + target, e);
×
210
    }
1✔
211
  }
1✔
212

213
  @Override
214
  public String download(String url) {
215

216
    this.context.debug("Downloading text body from {}", url);
10✔
217
    return httpGetAsString(url);
3✔
218
  }
219

220
  @Override
221
  public void mkdirs(Path directory) {
222

223
    if (Files.isDirectory(directory)) {
5✔
224
      return;
1✔
225
    }
226
    this.context.trace("Creating directory {}", directory);
10✔
227
    try {
228
      Files.createDirectories(directory);
5✔
229
    } catch (IOException e) {
×
230
      throw new IllegalStateException("Failed to create directory " + directory, e);
×
231
    }
1✔
232
  }
1✔
233

234
  @Override
235
  public boolean isFile(Path file) {
236

237
    if (!Files.exists(file)) {
5!
238
      this.context.trace("File {} does not exist", file);
×
239
      return false;
×
240
    }
241
    if (Files.isDirectory(file)) {
5!
242
      this.context.trace("Path {} is a directory but a regular file was expected", file);
×
243
      return false;
×
244
    }
245
    return true;
2✔
246
  }
247

248
  @Override
249
  public boolean isExpectedFolder(Path folder) {
250

251
    if (Files.isDirectory(folder)) {
5✔
252
      return true;
2✔
253
    }
254
    this.context.warning("Expected folder was not found at {}", folder);
10✔
255
    return false;
2✔
256
  }
257

258
  @Override
259
  public String checksum(Path file, String hashAlgorithm) {
260

261
    MessageDigest md;
262
    try {
263
      md = MessageDigest.getInstance(hashAlgorithm);
×
264
    } catch (NoSuchAlgorithmException e) {
×
265
      throw new IllegalStateException("No such hash algorithm " + hashAlgorithm, e);
×
266
    }
×
267
    byte[] buffer = new byte[1024];
×
268
    try (InputStream is = Files.newInputStream(file); DigestInputStream dis = new DigestInputStream(is, md)) {
×
269
      int read = 0;
×
270
      while (read >= 0) {
×
271
        read = dis.read(buffer);
×
272
      }
273
    } catch (Exception e) {
×
274
      throw new IllegalStateException("Failed to read and hash file " + file, e);
×
275
    }
×
276
    byte[] digestBytes = md.digest();
×
277
    return HexUtil.toHexString(digestBytes);
×
278
  }
279

280
  @Override
281
  public boolean isJunction(Path path) {
282

283
    if (!SystemInfoImpl.INSTANCE.isWindows()) {
3!
284
      return false;
2✔
285
    }
286
    try {
287
      BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
×
288
      return attr.isOther() && attr.isDirectory();
×
289
    } catch (NoSuchFileException e) {
×
290
      return false; // file doesn't exist
×
291
    } catch (IOException e) {
×
292
      // errors in reading the attributes of the file
293
      throw new IllegalStateException("An unexpected error occurred whilst checking if the file: " + path + " is a junction", e);
×
294
    }
295
  }
296

297
  @Override
298
  public Path backup(Path fileOrFolder) {
299

300
    if ((fileOrFolder != null) && (Files.isSymbolicLink(fileOrFolder) || isJunction(fileOrFolder))) {
9!
301
      delete(fileOrFolder);
4✔
302
    } else if ((fileOrFolder != null) && Files.exists(fileOrFolder)) {
7!
303
      LocalDateTime now = LocalDateTime.now();
2✔
304
      String date = DateTimeUtil.formatDate(now, true);
4✔
305
      String time = DateTimeUtil.formatTime(now);
3✔
306
      String filename = fileOrFolder.getFileName().toString();
4✔
307
      Path backupPath = this.context.getIdeHome().resolve(IdeContext.FOLDER_BACKUPS).resolve(date).resolve(time + "_" + filename);
12✔
308
      backupPath = appendParentPath(backupPath, fileOrFolder.getParent(), 2);
6✔
309
      mkdirs(backupPath);
3✔
310
      Path target = backupPath.resolve(filename);
4✔
311
      this.context.info("Creating backup by moving {} to {}", fileOrFolder, target);
14✔
312
      move(fileOrFolder, target);
6✔
313
      return target;
2✔
314
    } else {
315
      this.context.trace("Backup of {} skipped as the path does not exist.", fileOrFolder);
10✔
316
    }
317
    return fileOrFolder;
2✔
318
  }
319

320
  private static Path appendParentPath(Path path, Path parent, int max) {
321

322
    if ((parent == null) || (max <= 0)) {
4!
323
      return path;
2✔
324
    }
325
    return appendParentPath(path, parent.getParent(), max - 1).resolve(parent.getFileName());
11✔
326
  }
327

328
  @Override
329
  public void move(Path source, Path targetDir, StandardCopyOption... copyOptions) {
330

331
    this.context.trace("Moving {} to {}", source, targetDir);
14✔
332
    try {
333
      Files.move(source, targetDir, copyOptions);
5✔
334
    } catch (IOException e) {
×
335
      String fileType = Files.isSymbolicLink(source) ? "symlink" : isJunction(source) ? "junction" : Files.isDirectory(source) ? "directory" : "file";
×
336
      String message = "Failed to move " + fileType + ": " + source + " to " + targetDir + ".";
×
337
      if (this.context.getSystemInfo().isWindows()) {
×
338
        message = message + "\n" + WINDOWS_FILE_LOCK_WARNING;
×
339
      }
340
      throw new IllegalStateException(message, e);
×
341
    }
1✔
342
  }
1✔
343

344
  @Override
345
  public void copy(Path source, Path target, FileCopyMode mode, PathCopyListener listener) {
346

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

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

391
    if (Files.isDirectory(source)) {
5✔
392
      mkdirs(target);
3✔
393
      try (Stream<Path> childStream = Files.list(source)) {
3✔
394
        Iterator<Path> iterator = childStream.iterator();
3✔
395
        while (iterator.hasNext()) {
3✔
396
          Path child = iterator.next();
4✔
397
          copyRecursive(child, target.resolve(child.getFileName().toString()), mode, listener);
10✔
398
        }
1✔
399
      }
400
      listener.onCopy(source, target, true);
6✔
401
    } else if (Files.exists(source)) {
5!
402
      if (mode.isOverride()) {
3✔
403
        delete(target);
3✔
404
      }
405
      this.context.trace("Starting to {} {} to {}", mode.getOperation(), source, target);
19✔
406
      Files.copy(source, target);
6✔
407
      listener.onCopy(source, target, false);
6✔
408
    } else {
409
      throw new IOException("Path " + source + " does not exist.");
×
410
    }
411
  }
1✔
412

413
  /**
414
   * 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
415
   * {@link Path} that is neither a symbolic link nor a Windows junction.
416
   *
417
   * @param path the {@link Path} to delete.
418
   */
419
  private void deleteLinkIfExists(Path path) {
420

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

424
    assert !(isSymlink && isJunction);
5!
425

426
    if (isJunction || isSymlink) {
4!
427
      this.context.info("Deleting previous " + (isJunction ? "junction" : "symlink") + " at " + path);
9!
428
      try {
429
        Files.delete(path);
2✔
430
      } catch (IOException e) {
×
431
        throw new IllegalStateException("Failed to delete link at " + path, e);
×
432
      }
1✔
433
    }
434
  }
1✔
435

436
  /**
437
   * Adapts the given {@link Path} to be relative or absolute depending on the given {@code relative} flag. Additionally, {@link Path#toRealPath(LinkOption...)}
438
   * is applied to {@code target}.
439
   *
440
   * @param target the {@link Path} the link should point to and that is to be adapted.
441
   * @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}.
442
   * @param relative the {@code relative} flag.
443
   * @return the adapted {@link Path}.
444
   * @see #symlink(Path, Path, boolean)
445
   */
446
  private Path adaptPath(Path target, Path link, boolean relative) {
447

448
    if (!target.isAbsolute()) {
3✔
449
      target = link.resolveSibling(target);
4✔
450
    }
451
    try {
452
      target = target.toRealPath(LinkOption.NOFOLLOW_LINKS); // to transform ../d1/../d2 to ../d2
9✔
453
    } catch (IOException e) {
×
454
      throw new RuntimeException("Failed to get real path of " + target, e);
×
455
    }
1✔
456
    if (relative) {
2✔
457
      target = link.getParent().relativize(target);
5✔
458
      // to make relative links like this work: dir/link -> dir
459
      target = (target.toString().isEmpty()) ? Path.of(".") : target;
11✔
460
    }
461
    return target;
2✔
462
  }
463

464
  /**
465
   * Creates a Windows link using mklink at {@code link} pointing to {@code target}.
466
   *
467
   * @param target the {@link Path} the link will point to.
468
   * @param link the {@link Path} where to create the link.
469
   * @param type the {@link PathLinkType}.
470
   */
471
  private void mklinkOnWindows(Path target, Path link, PathLinkType type) {
472

473
    this.context.trace("Creating a Windows link at {} pointing to {}", link, target);
×
474
    ProcessContext pc = this.context.newProcess().executable("cmd")
×
475
        .addArgs("/c", "mklink", type.getMklinkOption());
×
476
    if (type == PathLinkType.SYMBOLIC_LINK && Files.isDirectory(target)) {
×
477
      pc.addArg("/j");
×
478
      target = target.toAbsolutePath();
×
479
    }
480
    pc = pc.addArgs(link.toString(), target.toString());
×
481
    ProcessResult result = pc
×
482
        .run(ProcessMode.DEFAULT);
×
483
    result.failOnError();
×
484
  }
×
485

486
  @Override
487
  public void link(Path target, Path link, boolean relative, PathLinkType type) {
488

489
    final Path finalTarget;
490
    try {
491
      finalTarget = adaptPath(target, link, relative);
6✔
492
    } catch (Exception e) {
×
493
      throw new IllegalStateException("Failed to adapt target (" + target + ") for link (" + link + ") and relative (" + relative + ")", e);
×
494
    }
1✔
495
    String relativeOrAbsolute = finalTarget.isAbsolute() ? "absolute" : "relative";
7✔
496
    this.context.debug("Creating {} {} at {} pointing to {}", relativeOrAbsolute, type, link, finalTarget);
22✔
497
    deleteLinkIfExists(link);
3✔
498
    try {
499
      if (type == PathLinkType.SYMBOLIC_LINK) {
3!
500
        Files.createSymbolicLink(link, finalTarget);
7✔
501
      } else if (type == PathLinkType.HARD_LINK) {
×
502
        Files.createLink(link, finalTarget);
×
503
      } else {
504
        throw new IllegalStateException("" + type);
×
505
      }
506
    } catch (FileSystemException e) {
×
507
      if (SystemInfoImpl.INSTANCE.isWindows()) {
×
508
        this.context.info(
×
509
            "Due to lack of permissions, Microsoft's mklink with junction had to be used to create a Symlink. See\n"
510
                + "https://github.com/devonfw/IDEasy/blob/main/documentation/symlink.adoc for further details. Error was: "
511
                + e.getMessage());
×
512
        mklinkOnWindows(finalTarget, link, type);
×
513
      } else {
514
        throw new RuntimeException(e);
×
515
      }
516
    } catch (IOException e) {
×
517
      throw new IllegalStateException(
×
518
          "Failed to create a " + relativeOrAbsolute + " " + type + " at " + link + " pointing to " + target, e);
519
    }
1✔
520
  }
1✔
521

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

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

528
  @Override
529
  public Path toCanonicalPath(Path path) {
530

531
    return toRealPath(path, false);
5✔
532
  }
533

534
  private Path toRealPath(Path path, boolean resolveLinks) {
535

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

552
  @Override
553
  public Path createTempDir(String name) {
554

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

573
  @Override
574
  public void extract(Path archiveFile, Path targetDir, Consumer<Path> postExtractHook, boolean extract) {
575

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

614
  private void postExtractHook(Consumer<Path> postExtractHook, Path properInstallDir) {
615

616
    if (postExtractHook != null) {
2✔
617
      postExtractHook.accept(properInstallDir);
3✔
618
    }
619
  }
1✔
620

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

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

645
  @Override
646
  public void extractZip(Path file, Path targetDir) {
647

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

665
  @SuppressWarnings("unchecked")
666
  private void onFileCopiedFromZip(Path source, Path target, boolean directory, IdeProgressBar progressBar) {
667

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

684
  @Override
685
  public void extractTar(Path file, Path targetDir, TarCompression compression) {
686

687
    extractArchive(file, targetDir, in -> new TarArchiveInputStream(compression.unpack(in)));
13✔
688
  }
1✔
689

690
  @Override
691
  public void extractJar(Path file, Path targetDir) {
692

693
    extractZip(file, targetDir);
4✔
694
  }
1✔
695

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

702
    // Ensure that only the last 9 bits are considered
703
    permissions &= 0b111111111;
4✔
704

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

712
    return permissionStringBuilder.toString();
3✔
713
  }
714

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

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

719
    final List<PathLink> links = new ArrayList<>();
4✔
720
    try (InputStream is = Files.newInputStream(file);
5✔
721
        ArchiveInputStream<?> ais = unpacker.apply(is);
5✔
722
        IdeProgressBar pb = this.context.newProgressbarForExtracting(getFileSize(file))) {
7✔
723

724
      final boolean isTar = (ais instanceof TarArchiveInputStream);
3✔
725
      final boolean isWindows = this.context.getSystemInfo().isWindows();
5✔
726
      final Path root = targetDir.toAbsolutePath().normalize();
4✔
727

728
      ArchiveEntry entry = ais.getNextEntry();
3✔
729
      while (entry != null) {
2✔
730
        String entryName = entry.getName();
3✔
731
        Path entryPath = resolveRelativePathSecure(entryName, root);
5✔
732
        PathPermissions permissions = null;
2✔
733
        PathLinkType linkType = null;
2✔
734
        if (entry instanceof TarArchiveEntry tae) {
6!
735
          if (tae.isSymbolicLink()) {
3!
736
            linkType = PathLinkType.SYMBOLIC_LINK;
×
737
          } else if (tae.isLink()) {
3!
738
            linkType = PathLinkType.HARD_LINK;
×
739
          }
740
          if (linkType == null) {
2!
741
            permissions = PathPermissions.of(tae.getMode());
5✔
742
          } else {
743
            Path parent = entryPath.getParent();
×
744
            String linkName = tae.getLinkName();
×
745
            Path linkTarget = parent.resolve(linkName).normalize();
×
746
            Path target = resolveRelativePathSecure(linkTarget, root, linkName);
×
747
            links.add(new PathLink(entryPath, target, linkType));
×
748
            mkdirs(parent);
×
749
          }
750
        }
751
        if (entry.isDirectory()) {
3✔
752
          mkdirs(entryPath);
4✔
753
        } else if (linkType == null) { // regular file
2!
754
          mkdirs(entryPath.getParent());
4✔
755
          Files.copy(ais, entryPath, StandardCopyOption.REPLACE_EXISTING);
10✔
756
          // POSIX perms on non-Windows
757
          if (!isWindows && (permissions != null)) {
4!
758
            setFilePermissions(entryPath, permissions, false);
5✔
759
          }
760
        }
761
        pb.stepBy(Math.max(0L, entry.getSize()));
6✔
762
        entry = ais.getNextEntry();
3✔
763
      }
1✔
764
      // post process links
765
      for (PathLink link : links) {
6!
766
        link(link);
×
767
      }
×
768
    } catch (Exception e) {
×
769
      throw new IllegalStateException("Failed to extract " + file + " to " + targetDir, e);
×
770
    }
1✔
771
  }
1✔
772

773
  private Path resolveRelativePathSecure(String entryName, Path root) {
774

775
    Path entryPath = root.resolve(entryName).normalize();
5✔
776
    return resolveRelativePathSecure(entryPath, root, entryName);
6✔
777
  }
778

779
  private Path resolveRelativePathSecure(Path entryPath, Path root, String entryName) {
780

781
    if (!entryPath.startsWith(root)) {
4!
782
      throw new IllegalStateException("Preventing path traversal attack from " + entryName + " to " + entryPath + " leaving " + root);
×
783
    }
784
    return entryPath;
2✔
785
  }
786

787

788
  @Override
789
  public void extractDmg(Path file, Path targetDir) {
790

791
    this.context.info("Extracting DMG file {} to {}", file, targetDir);
×
792
    assert this.context.getSystemInfo().isMac();
×
793

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

805
    copy(appPath, targetDir, FileCopyMode.COPY_TREE_OVERRIDE_TREE);
×
806
    pc.addArgs("detach", "-force", mountPath);
×
807
    pc.run();
×
808
  }
×
809

810
  @Override
811
  public void extractMsi(Path file, Path targetDir) {
812

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

820
  @Override
821
  public void extractPkg(Path file, Path targetDir) {
822

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

833
  @Override
834
  public void compress(Path dir, OutputStream out, String format) {
835

836
    String extension = FilenameUtil.getExtension(format);
3✔
837
    TarCompression tarCompression = TarCompression.of(extension);
3✔
838
    if (tarCompression != null) {
2!
839
      compressTar(dir, out, tarCompression);
6✔
840
    } else if (extension.equals("zip")) {
×
841
      compressZip(dir, out);
×
842
    } else {
843
      throw new IllegalArgumentException("Unsupported extension: " + extension);
×
844
    }
845
  }
1✔
846

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

858
  @Override
859
  public void compressTarGz(Path dir, OutputStream out) {
860
    try (GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(out)) {
5✔
861
      compressTarOrThrow(dir, gzOut);
4✔
862
    } catch (IOException e) {
×
863
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar.gz file.", e);
×
864
    }
1✔
865
  }
1✔
866

867
  @Override
868
  public void compressTarBzip2(Path dir, OutputStream out) {
869
    try (BZip2CompressorOutputStream bzip2Out = new BZip2CompressorOutputStream(out)) {
×
870
      compressTarOrThrow(dir, bzip2Out);
×
871
    } catch (IOException e) {
×
872
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar.bz2 file.", e);
×
873
    }
×
874
  }
×
875

876
  @Override
877
  public void compressTar(Path dir, OutputStream out) {
878
    try {
879
      compressTarOrThrow(dir, out);
×
880
    } catch (IOException e) {
×
881
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar file.", e);
×
882
    }
×
883
  }
×
884

885
  private void compressTarOrThrow(Path dir, OutputStream out) throws IOException {
886
    try (TarArchiveOutputStream tarOut = new TarArchiveOutputStream(out)) {
5✔
887
      compressRecursive(dir, tarOut, "");
5✔
888
      tarOut.finish();
2✔
889
    }
890
  }
1✔
891

892
  @Override
893
  public void compressZip(Path dir, OutputStream out) {
894
    try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(out)) {
×
895
      compressRecursive(dir, zipOut, "");
×
896
      zipOut.finish();
×
897
    } catch (IOException e) {
×
898
      throw new IllegalStateException("Failed to compress directory " + dir + " to zip file.", e);
×
899
    }
×
900
  }
×
901

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

946
  @Override
947
  public void delete(Path path) {
948

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

965
  private void deleteRecursive(Path path) throws IOException {
966

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

984
  @Override
985
  public Path findFirst(Path dir, Predicate<Path> filter, boolean recursive) {
986

987
    try {
988
      if (!Files.isDirectory(dir)) {
5✔
989
        return null;
2✔
990
      }
991
      return findFirstRecursive(dir, filter, recursive);
6✔
992
    } catch (IOException e) {
×
993
      throw new IllegalStateException("Failed to search for file in " + dir, e);
×
994
    }
995
  }
996

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

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

1025
  @Override
1026
  public List<Path> listChildrenMapped(Path dir, Function<Path, Path> filter) {
1027

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

1054
  @Override
1055
  public boolean isEmptyDir(Path dir) {
1056

1057
    return listChildren(dir, f -> true).isEmpty();
8✔
1058
  }
1059

1060
  private long getFileSize(Path file) {
1061

1062
    try {
1063
      return Files.size(file);
3✔
1064
    } catch (IOException e) {
×
1065
      this.context.warning(e.getMessage(), e);
×
1066
      return 0;
×
1067
    }
1068
  }
1069

1070
  private long getFileSizeRecursive(Path path) {
1071

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

1089
  @Override
1090
  public Path findExistingFile(String fileName, List<Path> searchDirs) {
1091

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

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

1124
      // Windows
1125
      DosFileAttributeView dos = Files.getFileAttributeView(file, DosFileAttributeView.class);
×
1126
      if (dos != null) {
×
1127
        dos.setReadOnly(!writable);
×
1128
        return true;
×
1129
      }
1130

1131
      this.context.debug("Failed to set writing permission for file {}", file);
×
1132
      return false;
×
1133

1134
    } catch (IOException e) {
1✔
1135
      this.context.debug("Error occurred when trying to set writing permission for file " + file + ": " + e);
8✔
1136
      return false;
2✔
1137
    }
1138
  }
1139

1140
  @Override
1141
  public void makeExecutable(Path path, boolean confirm) {
1142

1143
    if (Files.exists(path)) {
5✔
1144
      if (skipPermissionsIfWindows(path)) {
4!
1145
        return;
×
1146
      }
1147
      Set<PosixFilePermission> existingPosixPermissions;
1148
      try {
1149
        // Read the current file permissions
1150
        existingPosixPermissions = Files.getPosixFilePermissions(path);
5✔
1151
      } catch (IOException e) {
×
1152
        throw new RuntimeException("Failed to get permissions for " + path, e);
×
1153
      }
1✔
1154

1155
      PathPermissions existingPermissions = PathPermissions.of(existingPosixPermissions);
3✔
1156
      PathPermissions executablePermissions = existingPermissions.makeExecutable();
3✔
1157
      boolean update = (executablePermissions != existingPermissions);
7✔
1158
      if (update) {
2✔
1159
        if (confirm) {
2!
1160
          boolean yesContinue = this.context.question(
×
1161
              "We want to execute {} but this command seems to lack executable permissions!\n"
1162
                  + "Most probably the tool vendor did forgot to add x-flags in the binary release package.\n"
1163
                  + "Before running the command, we suggest to set executable permissions to the file:\n"
1164
                  + "{}\n"
1165
                  + "For security reasons we ask for your confirmation so please check this request.\n"
1166
                  + "Changing permissions from {} to {}.\n"
1167
                  + "Do you confirm to make the command executable before running it?", path.getFileName(), path, existingPermissions, executablePermissions);
×
1168
          if (!yesContinue) {
×
1169
            return;
×
1170
          }
1171
        }
1172
        setFilePermissions(path, executablePermissions, false);
6✔
1173
      } else {
1174
        this.context.trace("Executable flags already present so no need to set them for file {}", path);
10✔
1175
      }
1176
    } else {
1✔
1177
      this.context.warning("Cannot set executable flag on file that does not exist: {}", path);
10✔
1178
    }
1179
  }
1✔
1180

1181
  @Override
1182
  public void setFilePermissions(Path path, PathPermissions permissions, boolean logErrorAndContinue) {
1183

1184
    if (skipPermissionsIfWindows(path)) {
4!
1185
      return;
×
1186
    }
1187
    try {
1188
      this.context.debug("Setting permissions for {} to {}", path, permissions);
14✔
1189
      // Set the new permissions
1190
      Files.setPosixFilePermissions(path, permissions.toPosix());
5✔
1191
    } catch (IOException e) {
×
1192
      if (logErrorAndContinue) {
×
1193
        this.context.warning().log(e, "Failed to set permissions to {} for path {}", permissions, path);
×
1194
      } else {
1195
        throw new RuntimeException("Failed to set permissions to " + permissions + " for path " + path, e);
×
1196
      }
1197
    }
1✔
1198
  }
1✔
1199

1200
  private boolean skipPermissionsIfWindows(Path path) {
1201
    if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
1202
      this.context.trace("Windows does not have file permissions hence omitting for {}", path);
×
1203
      return true;
×
1204
    }
1205
    return false;
2✔
1206
  }
1207

1208
  @Override
1209
  public void touch(Path file) {
1210

1211
    if (Files.exists(file)) {
5✔
1212
      try {
1213
        Files.setLastModifiedTime(file, FileTime.fromMillis(System.currentTimeMillis()));
5✔
1214
      } catch (IOException e) {
×
1215
        throw new IllegalStateException("Could not update modification-time of " + file, e);
×
1216
      }
1✔
1217
    } else {
1218
      try {
1219
        Files.createFile(file);
5✔
1220
      } catch (IOException e) {
1✔
1221
        throw new IllegalStateException("Could not create empty file " + file, e);
8✔
1222
      }
1✔
1223
    }
1224
  }
1✔
1225

1226
  @Override
1227
  public String readFileContent(Path file) {
1228

1229
    this.context.trace("Reading content of file from {}", file);
10✔
1230
    if (!Files.exists((file))) {
5!
1231
      this.context.debug("File {} does not exist", file);
×
1232
      return null;
×
1233
    }
1234
    try {
1235
      String content = Files.readString(file);
3✔
1236
      this.context.trace("Completed reading {} character(s) from file {}", content.length(), file);
16✔
1237
      return content;
2✔
1238
    } catch (IOException e) {
×
1239
      throw new IllegalStateException("Failed to read file " + file, e);
×
1240
    }
1241
  }
1242

1243
  @Override
1244
  public void writeFileContent(String content, Path file, boolean createParentDir) {
1245

1246
    if (createParentDir) {
2✔
1247
      mkdirs(file.getParent());
4✔
1248
    }
1249
    if (content == null) {
2!
1250
      content = "";
×
1251
    }
1252
    this.context.trace("Writing content with {} character(s) to file {}", content.length(), file);
16✔
1253
    if (Files.exists(file)) {
5✔
1254
      this.context.info("Overriding content of file {}", file);
10✔
1255
    }
1256
    try {
1257
      Files.writeString(file, content);
6✔
1258
      this.context.trace("Wrote content to file {}", file);
10✔
1259
    } catch (IOException e) {
×
1260
      throw new RuntimeException("Failed to write file " + file, e);
×
1261
    }
1✔
1262
  }
1✔
1263

1264
  @Override
1265
  public List<String> readFileLines(Path file) {
1266

1267
    this.context.trace("Reading content of file from {}", file);
10✔
1268
    if (!Files.exists(file)) {
5✔
1269
      this.context.warning("File {} does not exist", file);
10✔
1270
      return null;
2✔
1271
    }
1272
    try {
1273
      List<String> content = Files.readAllLines(file);
3✔
1274
      this.context.trace("Completed reading {} lines from file {}", content.size(), file);
16✔
1275
      return content;
2✔
1276
    } catch (IOException e) {
×
1277
      throw new IllegalStateException("Failed to read file " + file, e);
×
1278
    }
1279
  }
1280

1281
  @Override
1282
  public void writeFileLines(List<String> content, Path file, boolean createParentDir) {
1283

1284
    if (createParentDir) {
2!
1285
      mkdirs(file.getParent());
×
1286
    }
1287
    if (content == null) {
2!
1288
      content = List.of();
×
1289
    }
1290
    this.context.trace("Writing content with {} lines to file {}", content.size(), file);
16✔
1291
    if (Files.exists(file)) {
5✔
1292
      this.context.debug("Overriding content of file {}", file);
10✔
1293
    }
1294
    try {
1295
      Files.write(file, content);
6✔
1296
      this.context.trace("Wrote content to file {}", file);
10✔
1297
    } catch (IOException e) {
×
1298
      throw new RuntimeException("Failed to write file " + file, e);
×
1299
    }
1✔
1300
  }
1✔
1301

1302
  @Override
1303
  public void readProperties(Path file, Properties properties) {
1304

1305
    try (Reader reader = Files.newBufferedReader(file)) {
3✔
1306
      properties.load(reader);
3✔
1307
      this.context.debug("Successfully loaded {} properties from {}", properties.size(), file);
16✔
1308
    } catch (IOException e) {
×
1309
      throw new IllegalStateException("Failed to read properties file: " + file, e);
×
1310
    }
1✔
1311
  }
1✔
1312

1313
  @Override
1314
  public void writeProperties(Properties properties, Path file, boolean createParentDir) {
1315

1316
    if (createParentDir) {
2✔
1317
      mkdirs(file.getParent());
4✔
1318
    }
1319
    try (Writer writer = Files.newBufferedWriter(file)) {
5✔
1320
      properties.store(writer, null); // do not get confused - Java still writes a date/time header that cannot be omitted
4✔
1321
      this.context.debug("Successfully saved {} properties to {}", properties.size(), file);
16✔
1322
    } catch (IOException e) {
×
1323
      throw new IllegalStateException("Failed to save properties file during tests.", e);
×
1324
    }
1✔
1325
  }
1✔
1326

1327
  @Override
1328
  public void readIniFile(Path file, IniFile iniFile) {
1329
    if (!Files.exists(file)) {
5!
1330
      this.context.debug("INI file {} does not exist.", iniFile);
×
1331
      return;
×
1332
    }
1333
    List<String> iniLines = readFileLines(file);
4✔
1334
    IniSection currentIniSection = iniFile.getInitialSection();
3✔
1335
    for (String line : iniLines) {
10✔
1336
      if (line.trim().startsWith("[")) {
5✔
1337
        currentIniSection = iniFile.getOrCreateSection(line);
5✔
1338
      } else if (line.isBlank() || IniComment.COMMENT_SYMBOLS.contains(line.trim().charAt(0))) {
11✔
1339
        currentIniSection.addComment(line);
4✔
1340
      } else {
1341
        int index = line.indexOf('=');
4✔
1342
        if (index > 0) {
2!
1343
          currentIniSection.setProperty(line);
3✔
1344
        }
1345
      }
1346
    }
1✔
1347
  }
1✔
1348

1349
  @Override
1350
  public void writeIniFile(IniFile iniFile, Path file, boolean createParentDir) {
1351
    String iniString = iniFile.toString();
3✔
1352
    writeFileContent(iniString, file, createParentDir);
5✔
1353
  }
1✔
1354

1355
  @Override
1356
  public Duration getFileAge(Path path) {
1357
    if (Files.exists(path)) {
5✔
1358
      try {
1359
        long currentTime = System.currentTimeMillis();
2✔
1360
        long fileModifiedTime = Files.getLastModifiedTime(path).toMillis();
6✔
1361
        return Duration.ofMillis(currentTime - fileModifiedTime);
5✔
1362
      } catch (IOException e) {
×
1363
        this.context.warning().log(e, "Could not get modification-time of {}.", path);
×
1364
      }
×
1365
    } else {
1366
      this.context.debug("Path {} is missing - skipping modification-time and file age check.", path);
10✔
1367
    }
1368
    return null;
2✔
1369
  }
1370

1371
  @Override
1372
  public boolean isFileAgeRecent(Path path, Duration cacheDuration) {
1373

1374
    Duration age = getFileAge(path);
4✔
1375
    if (age == null) {
2✔
1376
      return false;
2✔
1377
    }
1378
    context.debug("The path {} was last updated {} ago and caching duration is {}.", path, age, cacheDuration);
18✔
1379
    return (age.toMillis() <= cacheDuration.toMillis());
10✔
1380
  }
1381
}
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