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

devonfw / IDEasy / 18198769689

02 Oct 2025 04:09PM UTC coverage: 68.41% (-0.06%) from 68.465%
18198769689

Pull #1520

github

web-flow
Merge 579199924 into 3602dff9e
Pull Request #1520: #1509: fix permissions on tar creation (and extraction)

3434 of 5501 branches covered (62.43%)

Branch coverage included in aggregate %.

8992 of 12663 relevant lines covered (71.01%)

3.12 hits per line

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

64.75
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 Map<String, String> FS_ENV = Map.of("encoding", "UTF-8");
5✔
81

82
  private final IdeContext context;
83

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

91
    super();
2✔
92
    this.context = context;
3✔
93
  }
1✔
94

95
  @Override
96
  public void download(String url, Path target) {
97

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

116
  private void downloadViaHttp(String url, Path target) {
117

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

140
  private void downloadWithHttpVersion(String url, Path target, Version httpVersion) throws Exception {
141

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

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

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

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

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

187
  private void copyFileWithProgressBar(Path source, Path target) {
188

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

210
  @Override
211
  public String download(String url) {
212

213
    this.context.debug("Downloading text body from {}", url);
10✔
214
    return httpGetAsString(url);
3✔
215
  }
216

217
  @Override
218
  public void mkdirs(Path directory) {
219

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

231
  @Override
232
  public boolean isFile(Path file) {
233

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

245
  @Override
246
  public boolean isExpectedFolder(Path folder) {
247

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

255
  @Override
256
  public String checksum(Path file, String hashAlgorithm) {
257

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

277
  @Override
278
  public boolean isJunction(Path path) {
279

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

294
  @Override
295
  public Path backup(Path fileOrFolder) {
296

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

317
  private static Path appendParentPath(Path path, Path parent, int max) {
318

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

325
  @Override
326
  public void move(Path source, Path targetDir, StandardCopyOption... copyOptions) {
327

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

341
  @Override
342
  public void copy(Path source, Path target, FileCopyMode mode, PathCopyListener listener) {
343

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

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

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

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

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

421
    assert !(isSymlink && isJunction);
5!
422

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

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

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

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

470
    this.context.trace("Creating a Windows {} at {} pointing to {}", type, link, target);
×
471
    ProcessContext pc = this.context.newProcess().executable("cmd").addArgs("/c", "mklink", type.getMklinkOption());
×
472
    Path parent = link.getParent();
×
473
    if (parent == null) {
×
474
      parent = Path.of(".");
×
475
    }
476
    Path absolute = parent.resolve(target).toAbsolutePath().normalize();
×
477
    if (type == PathLinkType.SYMBOLIC_LINK && Files.isDirectory(absolute)) {
×
478
      pc = pc.addArg("/j");
×
479
      target = absolute;
×
480
    }
481
    pc = pc.addArgs(link.toString(), target.toString());
×
482
    ProcessResult result = pc.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("Failed to create a " + relativeOrAbsolute + " " + type + " at " + link + " pointing to " + target, e);
×
518
    }
1✔
519
  }
1✔
520

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

723
      final Path root = targetDir.toAbsolutePath().normalize();
4✔
724

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

770
  private Path resolveRelativePathSecure(String entryName, Path root) {
771

772
    Path entryPath = root.resolve(entryName).normalize();
5✔
773
    return resolveRelativePathSecure(entryPath, root, entryName);
6✔
774
  }
775

776
  private Path resolveRelativePathSecure(Path entryPath, Path root, String entryName) {
777

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

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

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

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

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

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

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

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

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

829
  @Override
830
  public void compress(Path dir, OutputStream out, String format) {
831

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

843
  @Override
844
  public void compressTar(Path dir, OutputStream out, TarCompression tarCompression) {
845

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

855
  @Override
856
  public void compressTarGz(Path dir, OutputStream out) {
857

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

865
  @Override
866
  public void compressTarBzip2(Path dir, OutputStream out) {
867

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

875
  @Override
876
  public void compressTar(Path dir, OutputStream out) {
877

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

887
    try (TarArchiveOutputStream tarOut = new TarArchiveOutputStream(out)) {
5✔
888
      compressRecursive(dir, tarOut, "");
5✔
889
      tarOut.finish();
2✔
890
    }
891
  }
1✔
892

893
  @Override
894
  public void compressZip(Path dir, OutputStream out) {
895

896
    try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(out)) {
×
897
      compressRecursive(dir, zipOut, "");
×
898
      zipOut.finish();
×
899
    } catch (IOException e) {
×
900
      throw new IllegalStateException("Failed to compress directory " + dir + " to zip file.", e);
×
901
    }
×
902
  }
×
903

904
  private <E extends ArchiveEntry> void compressRecursive(Path path, ArchiveOutputStream<E> out, String relativePath) {
905

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

942
  @Override
943
  public void delete(Path path) {
944

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

961
  private void deleteRecursive(Path path) throws IOException {
962

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

980
  @Override
981
  public Path findFirst(Path dir, Predicate<Path> filter, boolean recursive) {
982

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

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

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

1021
  @Override
1022
  public List<Path> listChildrenMapped(Path dir, Function<Path, Path> filter) {
1023

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

1050
  @Override
1051
  public boolean isEmptyDir(Path dir) {
1052

1053
    return listChildren(dir, f -> true).isEmpty();
8✔
1054
  }
1055

1056
  private long getFileSize(Path file) {
1057

1058
    try {
1059
      return Files.size(file);
3✔
1060
    } catch (IOException e) {
×
1061
      this.context.warning(e.getMessage(), e);
×
1062
      return 0;
×
1063
    }
1064
  }
1065

1066
  private long getFileSizeRecursive(Path path) {
1067

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

1085
  @Override
1086
  public Path findExistingFile(String fileName, List<Path> searchDirs) {
1087

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

1101
  @Override
1102
  public boolean setWritable(Path file, boolean writable) {
1103

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

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

1128
      this.context.debug("Failed to set writing permission for file {}", file);
×
1129
      return false;
×
1130

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

1137
  @Override
1138
  public void makeExecutable(Path path, boolean confirm) {
1139

1140
    if (Files.exists(path)) {
5✔
1141
      if (skipPermissionsIfWindows(path)) {
4!
1142
        return;
×
1143
      }
1144
      PathPermissions existingPermissions = getFilePermissions(path);
4✔
1145
      PathPermissions executablePermissions = existingPermissions.makeExecutable();
3✔
1146
      boolean update = (executablePermissions != existingPermissions);
7✔
1147
      if (update) {
2✔
1148
        if (confirm) {
2!
1149
          boolean yesContinue = this.context.question(
×
1150
              "We want to execute {} but this command seems to lack executable permissions!\n"
1151
                  + "Most probably the tool vendor did forgot to add x-flags in the binary release package.\n"
1152
                  + "Before running the command, we suggest to set executable permissions to the file:\n"
1153
                  + "{}\n"
1154
                  + "For security reasons we ask for your confirmation so please check this request.\n"
1155
                  + "Changing permissions from {} to {}.\n"
1156
                  + "Do you confirm to make the command executable before running it?", path.getFileName(), path, existingPermissions, executablePermissions);
×
1157
          if (!yesContinue) {
×
1158
            return;
×
1159
          }
1160
        }
1161
        setFilePermissions(path, executablePermissions, false);
6✔
1162
      } else {
1163
        this.context.trace("Executable flags already present so no need to set them for file {}", path);
10✔
1164
      }
1165
    } else {
1✔
1166
      this.context.warning("Cannot set executable flag on file that does not exist: {}", path);
10✔
1167
    }
1168
  }
1✔
1169

1170
  @Override
1171
  public PathPermissions getFilePermissions(Path path) {
1172

1173
    PathPermissions pathPermissions;
1174
    String info = "";
2✔
1175
    if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
1176
      info = "mocked-";
×
1177
      if (Files.isDirectory(path)) {
×
1178
        pathPermissions = PathPermissions.MODE_RWX_RX_RX;
×
1179
      } else {
1180
        Path parent = path.getParent();
×
1181
        if ((parent != null) && (parent.getFileName().toString().equals("bin"))) {
×
1182
          pathPermissions = PathPermissions.MODE_RWX_RX_RX;
×
1183
        } else {
1184
          pathPermissions = PathPermissions.MODE_RW_R_R;
×
1185
        }
1186
      }
×
1187
    } else {
1188
      Set<PosixFilePermission> permissions;
1189
      try {
1190
        // Read the current file permissions
1191
        permissions = Files.getPosixFilePermissions(path);
5✔
1192
      } catch (IOException e) {
×
1193
        throw new RuntimeException("Failed to get permissions for " + path, e);
×
1194
      }
1✔
1195
      pathPermissions = PathPermissions.of(permissions);
3✔
1196
    }
1197
    this.context.trace("Read {}permissions of {} as {}.", info, path, pathPermissions);
18✔
1198
    return pathPermissions;
2✔
1199
  }
1200

1201
  @Override
1202
  public void setFilePermissions(Path path, PathPermissions permissions, boolean logErrorAndContinue) {
1203

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

1220
  private boolean skipPermissionsIfWindows(Path path) {
1221

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

1229
  @Override
1230
  public void touch(Path file) {
1231

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

1247
  @Override
1248
  public String readFileContent(Path file) {
1249

1250
    this.context.trace("Reading content of file from {}", file);
10✔
1251
    if (!Files.exists((file))) {
5!
1252
      this.context.debug("File {} does not exist", file);
×
1253
      return null;
×
1254
    }
1255
    try {
1256
      String content = Files.readString(file);
3✔
1257
      this.context.trace("Completed reading {} character(s) from file {}", content.length(), file);
16✔
1258
      return content;
2✔
1259
    } catch (IOException e) {
×
1260
      throw new IllegalStateException("Failed to read file " + file, e);
×
1261
    }
1262
  }
1263

1264
  @Override
1265
  public void writeFileContent(String content, Path file, boolean createParentDir) {
1266

1267
    if (createParentDir) {
2✔
1268
      mkdirs(file.getParent());
4✔
1269
    }
1270
    if (content == null) {
2!
1271
      content = "";
×
1272
    }
1273
    this.context.trace("Writing content with {} character(s) to file {}", content.length(), file);
16✔
1274
    if (Files.exists(file)) {
5✔
1275
      this.context.info("Overriding content of file {}", file);
10✔
1276
    }
1277
    try {
1278
      Files.writeString(file, content);
6✔
1279
      this.context.trace("Wrote content to file {}", file);
10✔
1280
    } catch (IOException e) {
×
1281
      throw new RuntimeException("Failed to write file " + file, e);
×
1282
    }
1✔
1283
  }
1✔
1284

1285
  @Override
1286
  public List<String> readFileLines(Path file) {
1287

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

1302
  @Override
1303
  public void writeFileLines(List<String> content, Path file, boolean createParentDir) {
1304

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

1323
  @Override
1324
  public void readProperties(Path file, Properties properties) {
1325

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

1334
  @Override
1335
  public void writeProperties(Properties properties, Path file, boolean createParentDir) {
1336

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

1348
  @Override
1349
  public void readIniFile(Path file, IniFile iniFile) {
1350

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

1371
  @Override
1372
  public void writeIniFile(IniFile iniFile, Path file, boolean createParentDir) {
1373

1374
    String iniString = iniFile.toString();
3✔
1375
    writeFileContent(iniString, file, createParentDir);
5✔
1376
  }
1✔
1377

1378
  @Override
1379
  public Duration getFileAge(Path path) {
1380

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
    this.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

© 2025 Coveralls, Inc