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

devonfw / IDEasy / 23186752287

17 Mar 2026 09:11AM UTC coverage: 70.34% (-0.3%) from 70.602%
23186752287

Pull #1756

github

web-flow
Merge bc867b664 into fd009eab8
Pull Request #1756: 1738: Fixed SymLink loop

4133 of 6482 branches covered (63.76%)

Branch coverage included in aggregate %.

10727 of 14644 relevant lines covered (73.25%)

3.08 hits per line

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

63.18
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.Objects;
37
import java.util.Properties;
38
import java.util.Set;
39
import java.util.function.Consumer;
40
import java.util.function.Function;
41
import java.util.function.Predicate;
42
import java.util.stream.Stream;
43

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

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

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

76
  private static final Logger LOG = LoggerFactory.getLogger(FileAccessImpl.class);
3✔
77

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

80
  private static final String WINDOWS_FILE_LOCK_WARNING =
81
      "On Windows, file operations could fail due to file locks. Please ensure the files in the moved directory are not in use. For further details, see: \n"
82
          + WINDOWS_FILE_LOCK_DOCUMENTATION_PAGE;
83

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

86
  private final IdeContext context;
87

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

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

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

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

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

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

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

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

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

165
    long contentLength = response.headers().firstValueAsLong("content-length").orElse(-1);
7✔
166
    if (contentLength < 0) {
4✔
167
      LOG.warn("Content-Length was not provided by download from {}", url);
4✔
168
    }
169

170
    byte[] data = new byte[1024];
3✔
171
    boolean fileComplete = false;
2✔
172
    int count;
173

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

192
  private void copyFileWithProgressBar(Path source, Path target) {
193

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

215
  @Override
216
  public String download(String url) {
217

218
    LOG.debug("Downloading text body from {}", url);
4✔
219
    return httpGetAsString(url);
3✔
220
  }
221

222
  @Override
223
  public void mkdirs(Path directory) {
224

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

236
  @Override
237
  public boolean isFile(Path file) {
238

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

250
  @Override
251
  public boolean isExpectedFolder(Path folder) {
252

253
    if (Files.isDirectory(folder)) {
5✔
254
      return true;
2✔
255
    }
256
    LOG.warn("Expected folder was not found at {}", folder);
4✔
257
    return false;
2✔
258
  }
259

260
  @Override
261
  public String checksum(Path file, String hashAlgorithm) {
262

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

282
  @Override
283
  public boolean isJunction(Path path) {
284

285
    if (!SystemInfoImpl.INSTANCE.isWindows()) {
3!
286
      return false;
2✔
287
    }
288
    try {
289
      BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
×
290
      return attr.isOther() && attr.isDirectory();
×
291
    } catch (NoSuchFileException e) {
×
292
      return false; // file doesn't exist
×
293
    } catch (IOException e) {
×
294
      // For broken junctions, reading attributes might fail with various IOExceptions.
295
      // In such cases, we should check if the path exists without following links.
296
      // If it exists but we can't read its attributes, it's likely a broken junction.
297
      if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
×
298
        LOG.debug("Path {} exists but attributes cannot be read, likely a broken junction: {}", path, e.getMessage());
×
299
        return true; // Assume it's a broken junction
×
300
      }
301
      // If it doesn't exist at all, it's not a junction
302
      return false;
×
303
    }
304
  }
305

306
  @Override
307
  public Path backup(Path fileOrFolder) {
308

309
    if ((fileOrFolder != null) && (Files.isSymbolicLink(fileOrFolder) || isJunction(fileOrFolder))) {
9!
310
      delete(fileOrFolder);
4✔
311
    } else if ((fileOrFolder != null) && Files.exists(fileOrFolder)) {
7!
312
      LOG.trace("Going to backup {}", fileOrFolder);
4✔
313
      LocalDateTime now = LocalDateTime.now();
2✔
314
      String date = DateTimeUtil.formatDate(now, true);
4✔
315
      String time = DateTimeUtil.formatTime(now);
3✔
316
      String filename = fileOrFolder.getFileName().toString();
4✔
317
      Path backupBaseDir = this.context.getIdeHome();
4✔
318
      if (backupBaseDir == null) {
2!
319
        backupBaseDir = this.context.getIdePath();
×
320
      }
321
      Path backupPath = backupBaseDir.resolve(IdeContext.FOLDER_BACKUPS).resolve(date).resolve(time + "_" + filename);
10✔
322
      backupPath = appendParentPath(backupPath, fileOrFolder.getParent(), 2);
6✔
323
      mkdirs(backupPath);
3✔
324
      Path target = backupPath.resolve(filename);
4✔
325
      LOG.info("Creating backup by moving {} to {}", fileOrFolder, target);
5✔
326
      move(fileOrFolder, target);
6✔
327
      return target;
2✔
328
    } else {
329
      LOG.trace("Backup of {} skipped as the path does not exist.", fileOrFolder);
4✔
330
    }
331
    return fileOrFolder;
2✔
332
  }
333

334
  private static Path appendParentPath(Path path, Path parent, int max) {
335

336
    if ((parent == null) || (max <= 0)) {
4!
337
      return path;
2✔
338
    }
339
    return appendParentPath(path, parent.getParent(), max - 1).resolve(parent.getFileName());
11✔
340
  }
341

342
  @Override
343
  public void move(Path source, Path targetDir, StandardCopyOption... copyOptions) {
344

345
    LOG.trace("Moving {} to {}", source, targetDir);
5✔
346
    try {
347
      Files.move(source, targetDir, copyOptions);
5✔
348
    } catch (IOException e) {
×
349
      String fileType = Files.isSymbolicLink(source) ? "symlink" : isJunction(source) ? "junction" : Files.isDirectory(source) ? "directory" : "file";
×
350
      String message = "Failed to move " + fileType + ": " + source + " to " + targetDir + ".";
×
351
      if (this.context.getSystemInfo().isWindows()) {
×
352
        message = message + "\n" + WINDOWS_FILE_LOCK_WARNING;
×
353
      }
354
      throw new IllegalStateException(message, e);
×
355
    }
1✔
356
  }
1✔
357

358
  @Override
359
  public void copy(Path source, Path target, FileCopyMode mode, PathCopyListener listener) {
360

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

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

405
    if (Files.isDirectory(source)) {
5✔
406
      mkdirs(target);
3✔
407
      try (Stream<Path> childStream = Files.list(source)) {
3✔
408
        Iterator<Path> iterator = childStream.iterator();
3✔
409
        while (iterator.hasNext()) {
3✔
410
          Path child = iterator.next();
4✔
411
          copyRecursive(child, target.resolve(child.getFileName().toString()), mode, listener);
10✔
412
        }
1✔
413
      }
414
      listener.onCopy(source, target, true);
6✔
415
    } else if (Files.exists(source)) {
5!
416
      if (mode.isOverride()) {
3✔
417
        delete(target);
3✔
418
      }
419
      LOG.trace("Starting to {} {} to {}", mode.getOperation(), source, target);
18✔
420
      Files.copy(source, target);
6✔
421
      listener.onCopy(source, target, false);
6✔
422
    } else {
423
      throw new IOException("Path " + source + " does not exist.");
×
424
    }
425
  }
1✔
426

427
  /**
428
   * 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
429
   * {@link Path} that is neither a symbolic link nor a Windows junction.
430
   *
431
   * @param path the {@link Path} to delete.
432
   */
433
  private void deleteLinkIfExists(Path path) {
434

435
    boolean isJunction = isJunction(path); // since broken junctions are not detected by Files.exists()
4✔
436
    boolean isSymlink = Files.exists(path, LinkOption.NOFOLLOW_LINKS) && Files.isSymbolicLink(path);
16!
437

438
    assert !(isSymlink && isJunction);
5!
439

440
    if (isJunction || isSymlink) {
4!
441
      LOG.info("Deleting previous " + (isJunction ? "junction" : "symlink") + " at " + path);
8!
442
      try {
443
        Files.delete(path);
2✔
444
      } catch (IOException e) {
×
445
        throw new IllegalStateException("Failed to delete link at " + path, e);
×
446
      }
1✔
447
    }
448
  }
1✔
449

450
  /**
451
   * Adapts the given {@link Path} to be relative or absolute depending on the given {@code relative} flag. Additionally, {@link Path#toRealPath(LinkOption...)}
452
   * is applied to {@code target}.
453
   *
454
   * @param link the {@link Path} the link should point to and that is to be adapted.
455
   * @param source the {@link Path} to the link. It is used to calculate the relative path to the {@code target} if {@code relative} is set to
456
   *     {@code true}.
457
   * @param relative the {@code relative} flag.
458
   * @return the adapted {@link Path}.
459
   * @see #symlink(Path, Path, boolean)
460
   */
461
  private Path adaptPath(Path source, Path link, boolean relative) {
462

463
    if (!source.isAbsolute()) {
3✔
464
      source = link.resolveSibling(source);
4✔
465
    }
466
    try {
467
      source = source.toRealPath(LinkOption.NOFOLLOW_LINKS); // to transform ../d1/../d2 to ../d2
9✔
468
    } catch (IOException e) {
×
469
      throw new RuntimeException("Failed to get real path of " + source, e);
×
470
    }
1✔
471
    if (relative) {
2✔
472
      source = link.getParent().relativize(source);
5✔
473
      // to make relative links like this work: dir/link -> dir
474
      source = (source.toString().isEmpty()) ? Path.of(".") : source;
11✔
475
    }
476
    return source;
2✔
477
  }
478

479
  /**
480
   * Creates a Windows link using mklink at {@code link} pointing to {@code target}.
481
   *
482
   * @param source the {@link Path} the link will point to.
483
   * @param link the {@link Path} where to create the link.
484
   * @param type the {@link PathLinkType}.
485
   */
486
  private void mklinkOnWindows(Path source, Path link, PathLinkType type, boolean relative) {
487

488
    Path absoluteSource = source.isAbsolute() ? source : link.getParent().resolve(source).normalize();
×
489
    Path finalSource = absoluteSource;
×
490
    Path finalLink = link;
×
491
    Path cwd = null;
×
492
    if (relative) {
×
493
      int count = getCommonNameCount(absoluteSource, link);
×
494
      if (count < 1) {
×
495
        LOG.error("Cannot create relative link at {} pointing to {} - falling back to absolute link", link, absoluteSource);
×
496
      } else {
497
        cwd = getPathStart(absoluteSource, count - 1);
×
498
        finalSource = getPathEnd(absoluteSource, count);
×
499
        finalLink = getPathEnd(link, count);
×
500
      }
501
    }
502

503
    if (type == PathLinkType.SYMBOLIC_LINK) {
×
504
      boolean directoryTarget = Files.isDirectory(absoluteSource, LinkOption.NOFOLLOW_LINKS);
×
505
      if (directoryTarget && runMklink(finalSource, finalLink, cwd, "/j")) {
×
506
        return;
×
507
      }
508
      if (runMklink(finalSource, finalLink, cwd, "/d")) {
×
509
        return;
×
510
      }
511
      throw new IllegalStateException("Failed to create Windows link at " + link + " pointing to " + source);
×
512
    }
513

514
    if (!runMklink(finalSource, finalLink, cwd, type.getMklinkOption())) {
×
515
      throw new IllegalStateException("Failed to create Windows link at " + link + " pointing to " + source);
×
516
    }
517
  }
×
518

519
  private boolean runMklink(Path source, Path link, Path cwd, String option) {
520

521
    LOG.trace("Creating a Windows link with mklink {} at {} pointing to {}", option, link, source);
×
522
    ProcessContext pc = this.context.newProcess().executable("cmd").addArgs("/c", "mklink", option);
×
523
    if (cwd != null) {
×
524
      pc.directory(cwd);
×
525
    }
526
    ProcessResult result = pc.addArgs(link.toString(), source.toString()).run(ProcessMode.DEFAULT);
×
527
    try {
528
      result.failOnError();
×
529
      return true;
×
530
    } catch (RuntimeException e) {
×
531
      LOG.debug("mklink {} failed for {} -> {}: {}", option, link, source, e.getMessage());
×
532
      return false;
×
533
    }
534
  }
535

536
  @Override
537
  public void link(Path source, Path link, boolean relative, PathLinkType type) {
538

539
    Path finalSource;
540
    try {
541
      finalSource = adaptPath(source, link, relative);
6✔
542
    } catch (Exception e) {
×
543
      throw new IllegalStateException("Failed to adapt target (" + source + ") for link (" + link + ") and relative (" + relative + ")", e);
×
544
    }
1✔
545
    String relativeOrAbsolute = relative ? "absolute" : "relative";
6✔
546
    LOG.debug("Creating {} {} at {} pointing to {}", relativeOrAbsolute, type, finalSource, source);
21✔
547
    deleteLinkIfExists(link);
3✔
548
    try {
549
      // Attention: JavaDoc and position of path arguments can be very confusing - see comment in #1736
550
      if (type == PathLinkType.SYMBOLIC_LINK) {
3!
551
        Files.createSymbolicLink(link, finalSource);
7✔
552
      } else if (type == PathLinkType.HARD_LINK) {
×
553
        Files.createLink(link, finalSource);
×
554
      } else {
555
        throw new IllegalStateException("" + type);
×
556
      }
557
    } catch (FileSystemException e) {
×
558
      if (SystemInfoImpl.INSTANCE.isWindows()) {
×
559
        LOG.info(
×
560
            "Due to lack of permissions, Microsoft's mklink with junction had to be used to create a Symlink. See\n"
561
                + "https://github.com/devonfw/IDEasy/blob/main/documentation/symlink.adoc for further details. Error was: "
562
                + e.getMessage());
×
563
        mklinkOnWindows(finalSource, link, type, relative);
×
564
      } else {
565
        throw new RuntimeException(e);
×
566
      }
567
    } catch (IOException e) {
×
568
      throw new IllegalStateException("Failed to create a " + relativeOrAbsolute + " " + type + " at " + link + " pointing to " + source, e);
×
569
    }
1✔
570
  }
1✔
571

572
  @Override
573
  public Path getPathStart(Path path, int nameEnd) {
574

575
    int count = path.getNameCount();
×
576
    int delta = count - nameEnd - 1;
×
577
    if (delta < 0) {
×
578
      throw new IllegalArgumentException("Cannot get start before segment " + nameEnd + " from path " + path + " that has only " + count + " segments.");
×
579
    }
580
    Path result = path;
×
581
    while (delta > 0) {
×
582
      result = result.getParent();
×
583
      delta--;
×
584
    }
585
    return result;
×
586
  }
587

588
  @Override
589
  public Path getPathEnd(Path path, int nameStart) {
590

591
    int count = path.getNameCount();
×
592
    if (nameStart > count) {
×
593
      throw new IllegalArgumentException("Cannot get end after segment " + nameStart + " from path " + path + " that has only " + count + " segments.");
×
594
    } else if (nameStart == count) {
×
595
      return Path.of(".");
×
596
    }
597
    Path result = path.getName(nameStart++);
×
598
    while (nameStart < count) {
×
599
      result = result.resolve(path.getName(nameStart++));
×
600
    }
601
    return result;
×
602
  }
603

604
  @Override
605
  public int getCommonNameCount(Path path1, Path path2) {
606

607
    if ((path1 == null) || (path2 == null) || !Objects.equals(path1.getRoot(), path2.getRoot())) {
×
608
      return -1;
×
609
    }
610
    int minNameCount = Math.min(path1.getNameCount(), path2.getNameCount());
×
611
    int i = 0;
×
612
    while (i < minNameCount) {
×
613
      Path segment1 = path1.getName(i);
×
614
      Path segment2 = path2.getName(i);
×
615
      if (!segment1.equals(segment2)) {
×
616
        break;
×
617
      }
618
      i++;
×
619
    }
×
620
    return i;
×
621
  }
622

623
  @Override
624
  public Path toRealPath(Path path) {
625

626
    return toRealPath(path, true);
5✔
627
  }
628

629
  @Override
630
  public Path toCanonicalPath(Path path) {
631

632
    return toRealPath(path, false);
5✔
633
  }
634

635
  private Path toRealPath(Path path, boolean resolveLinks) {
636

637
    try {
638
      Path realPath;
639
      if (resolveLinks) {
2✔
640
        realPath = path.toRealPath();
6✔
641
      } else {
642
        realPath = path.toRealPath(LinkOption.NOFOLLOW_LINKS);
9✔
643
      }
644
      if (!realPath.equals(path)) {
4✔
645
        LOG.trace("Resolved path {} to {}", path, realPath);
5✔
646
      }
647
      return realPath;
2✔
648
    } catch (IOException e) {
×
649
      throw new IllegalStateException("Failed to get real path for " + path, e);
×
650
    }
651
  }
652

653
  @Override
654
  public Path createTempDir(String name) {
655

656
    try {
657
      Path tmp = this.context.getTempPath();
4✔
658
      Path tempDir = tmp.resolve(name);
4✔
659
      int tries = 1;
2✔
660
      while (Files.exists(tempDir)) {
5!
661
        long id = System.nanoTime() & 0xFFFF;
×
662
        tempDir = tmp.resolve(name + "-" + id);
×
663
        tries++;
×
664
        if (tries > 200) {
×
665
          throw new IOException("Unable to create unique name!");
×
666
        }
667
      }
×
668
      return Files.createDirectory(tempDir);
5✔
669
    } catch (IOException e) {
×
670
      throw new IllegalStateException("Failed to create temporary directory with prefix '" + name + "'!", e);
×
671
    }
672
  }
673

674
  @Override
675
  public void extract(Path archiveFile, Path targetDir, Consumer<Path> postExtractHook, boolean extract) {
676

677
    if (Files.isDirectory(archiveFile)) {
5✔
678
      LOG.warn("Found directory for download at {} hence copying without extraction!", archiveFile);
4✔
679
      copy(archiveFile, targetDir, FileCopyMode.COPY_TREE_CONTENT);
5✔
680
      postExtractHook(postExtractHook, targetDir);
4✔
681
      return;
1✔
682
    } else if (!extract) {
2✔
683
      mkdirs(targetDir);
3✔
684
      move(archiveFile, targetDir.resolve(archiveFile.getFileName()));
9✔
685
      return;
1✔
686
    }
687
    Path tmpDir = createTempDir("extract-" + archiveFile.getFileName());
7✔
688
    LOG.trace("Trying to extract the file {} to {} and move it to {}.", archiveFile, tmpDir, targetDir);
17✔
689
    String filename = archiveFile.getFileName().toString();
4✔
690
    TarCompression tarCompression = TarCompression.of(filename);
3✔
691
    if (tarCompression != null) {
2✔
692
      extractTar(archiveFile, tmpDir, tarCompression);
6✔
693
    } else {
694
      String extension = FilenameUtil.getExtension(filename);
3✔
695
      if (extension == null) {
2!
696
        throw new IllegalStateException("Unknown archive format without extension - can not extract " + archiveFile);
×
697
      } else {
698
        LOG.trace("Determined file extension {}", extension);
4✔
699
      }
700
      switch (extension) {
8!
701
        case "zip" -> extractZip(archiveFile, tmpDir);
×
702
        case "jar" -> extractJar(archiveFile, tmpDir);
5✔
703
        case "dmg" -> extractDmg(archiveFile, tmpDir);
×
704
        case "msi" -> extractMsi(archiveFile, tmpDir);
×
705
        case "pkg" -> extractPkg(archiveFile, tmpDir);
×
706
        default -> throw new IllegalStateException("Unknown archive format " + extension + ". Can not extract " + archiveFile);
×
707
      }
708
    }
709
    Path properInstallDir = getProperInstallationSubDirOf(tmpDir, archiveFile);
5✔
710
    postExtractHook(postExtractHook, properInstallDir);
4✔
711
    move(properInstallDir, targetDir);
6✔
712
    delete(tmpDir);
3✔
713
  }
1✔
714

715
  private void postExtractHook(Consumer<Path> postExtractHook, Path properInstallDir) {
716

717
    if (postExtractHook != null) {
2✔
718
      postExtractHook.accept(properInstallDir);
3✔
719
    }
720
  }
1✔
721

722
  /**
723
   * @param path the {@link Path} to start the recursive search from.
724
   * @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
725
   *     item in their respective directory and {@code s} is not named "bin".
726
   */
727
  private Path getProperInstallationSubDirOf(Path path, Path archiveFile) {
728

729
    try (Stream<Path> stream = Files.list(path)) {
3✔
730
      Path[] subFiles = stream.toArray(Path[]::new);
8✔
731
      if (subFiles.length == 0) {
3!
732
        throw new CliException("The downloaded package " + archiveFile + " seems to be empty as you can check in the extracted folder " + path);
×
733
      } else if (subFiles.length == 1) {
4✔
734
        String filename = subFiles[0].getFileName().toString();
6✔
735
        if (!filename.equals(IdeContext.FOLDER_BIN) && !filename.equals(IdeContext.FOLDER_CONTENTS) && !filename.endsWith(".app") && Files.isDirectory(
19!
736
            subFiles[0])) {
737
          return getProperInstallationSubDirOf(subFiles[0], archiveFile);
9✔
738
        }
739
      }
740
      return path;
4✔
741
    } catch (IOException e) {
4!
742
      throw new IllegalStateException("Failed to get sub-files of " + path);
×
743
    }
744
  }
745

746
  @Override
747
  public void extractZip(Path file, Path targetDir) {
748

749
    LOG.info("Extracting ZIP file {} to {}", file, targetDir);
5✔
750
    URI uri = URI.create("jar:" + file.toUri());
6✔
751
    try (FileSystem fs = FileSystems.newFileSystem(uri, FS_ENV)) {
4✔
752
      long size = 0;
2✔
753
      for (Path root : fs.getRootDirectories()) {
11✔
754
        size += getFileSizeRecursive(root);
6✔
755
      }
1✔
756
      try (final IdeProgressBar progressBar = this.context.newProgressbarForExtracting(size)) {
5✔
757
        for (Path root : fs.getRootDirectories()) {
11✔
758
          copy(root, targetDir, FileCopyMode.EXTRACT, (s, t, d) -> onFileCopiedFromZip(s, t, d, progressBar));
15✔
759
        }
1✔
760
      }
761
    } catch (IOException e) {
×
762
      throw new IllegalStateException("Failed to extract " + file + " to " + targetDir, e);
×
763
    }
1✔
764
  }
1✔
765

766
  @SuppressWarnings("unchecked")
767
  private void onFileCopiedFromZip(Path source, Path target, boolean directory, IdeProgressBar progressBar) {
768

769
    if (directory) {
2✔
770
      return;
1✔
771
    }
772
    if (!this.context.getSystemInfo().isWindows()) {
5✔
773
      try {
774
        Object attribute = Files.getAttribute(source, "zip:permissions");
6✔
775
        if (attribute instanceof Set<?> permissionSet) {
6✔
776
          Files.setPosixFilePermissions(target, (Set<PosixFilePermission>) permissionSet);
4✔
777
        }
778
      } catch (Exception e) {
×
779
        LOG.error("Failed to transfer zip permissions for {}", target, e);
×
780
      }
1✔
781
    }
782
    progressBar.stepBy(getFileSize(target));
5✔
783
  }
1✔
784

785
  @Override
786
  public void extractTar(Path file, Path targetDir, TarCompression compression) {
787

788
    extractArchive(file, targetDir, in -> new TarArchiveInputStream(compression.unpack(in)));
13✔
789
  }
1✔
790

791
  @Override
792
  public void extractJar(Path file, Path targetDir) {
793

794
    extractZip(file, targetDir);
4✔
795
  }
1✔
796

797
  /**
798
   * @param permissions The integer as returned by {@link TarArchiveEntry#getMode()} that represents the file permissions of a file on a Unix file system.
799
   * @return A String representing the file permissions. E.g. "rwxrwxr-x" or "rw-rw-r--"
800
   */
801
  public static String generatePermissionString(int permissions) {
802

803
    // Ensure that only the last 9 bits are considered
804
    permissions &= 0b111111111;
4✔
805

806
    StringBuilder permissionStringBuilder = new StringBuilder("rwxrwxrwx");
5✔
807
    for (int i = 0; i < 9; i++) {
7✔
808
      int mask = 1 << i;
4✔
809
      char currentChar = ((permissions & mask) != 0) ? permissionStringBuilder.charAt(8 - i) : '-';
12✔
810
      permissionStringBuilder.setCharAt(8 - i, currentChar);
6✔
811
    }
812

813
    return permissionStringBuilder.toString();
3✔
814
  }
815

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

818
    LOG.info("Extracting TAR file {} to {}", file, targetDir);
5✔
819

820
    final List<PathLink> links = new ArrayList<>();
4✔
821
    try (InputStream is = Files.newInputStream(file);
5✔
822
        ArchiveInputStream<?> ais = unpacker.apply(is);
5✔
823
        IdeProgressBar pb = this.context.newProgressbarForExtracting(getFileSize(file))) {
7✔
824

825
      final Path root = targetDir.toAbsolutePath().normalize();
4✔
826

827
      ArchiveEntry entry = ais.getNextEntry();
3✔
828
      while (entry != null) {
2✔
829
        String entryName = entry.getName();
3✔
830
        Path entryPath = resolveRelativePathSecure(entryName, root);
5✔
831
        PathPermissions permissions = null;
2✔
832
        PathLinkType linkType = null;
2✔
833
        if (entry instanceof TarArchiveEntry tae) {
6!
834
          if (tae.isSymbolicLink()) {
3✔
835
            linkType = PathLinkType.SYMBOLIC_LINK;
3✔
836
          } else if (tae.isLink()) {
3!
837
            linkType = PathLinkType.HARD_LINK;
×
838
          }
839
          if (linkType == null) {
2✔
840
            permissions = PathPermissions.of(tae.getMode());
5✔
841
          } else {
842
            Path parent = entryPath.getParent();
3✔
843
            String sourcePathString = tae.getLinkName();
3✔
844
            Path source = parent.resolve(sourcePathString).normalize();
5✔
845
            source = resolveRelativePathSecure(source, root, sourcePathString);
6✔
846
            links.add(new PathLink(source, entryPath, linkType));
9✔
847
            mkdirs(parent);
3✔
848
          }
849
        }
850
        if (entry.isDirectory()) {
3✔
851
          mkdirs(entryPath);
4✔
852
        } else if (linkType == null) { // regular file
2✔
853
          mkdirs(entryPath.getParent());
4✔
854
          Files.copy(ais, entryPath, StandardCopyOption.REPLACE_EXISTING);
10✔
855
          // POSIX perms on non-Windows
856
          if (permissions != null) {
2!
857
            setFilePermissions(entryPath, permissions, false);
5✔
858
          }
859
        }
860
        pb.stepBy(Math.max(0L, entry.getSize()));
6✔
861
        entry = ais.getNextEntry();
3✔
862
      }
1✔
863
      // post process links
864
      for (PathLink link : links) {
10✔
865
        link(link);
3✔
866
      }
1✔
867
    } catch (Exception e) {
×
868
      throw new IllegalStateException("Failed to extract " + file + " to " + targetDir, e);
×
869
    }
1✔
870
  }
1✔
871

872
  private Path resolveRelativePathSecure(String entryName, Path root) {
873

874
    Path entryPath = root.resolve(entryName).normalize();
5✔
875
    return resolveRelativePathSecure(entryPath, root, entryName);
6✔
876
  }
877

878
  private Path resolveRelativePathSecure(Path entryPath, Path root, String entryName) {
879

880
    if (!entryPath.startsWith(root)) {
4!
881
      throw new IllegalStateException("Preventing path traversal attack from " + entryName + " to " + entryPath + " leaving " + root);
×
882
    }
883
    return entryPath;
2✔
884
  }
885

886
  @Override
887
  public void extractDmg(Path file, Path targetDir) {
888

889
    LOG.info("Extracting DMG file {} to {}", file, targetDir);
×
890
    assert this.context.getSystemInfo().isMac();
×
891

892
    Path mountPath = this.context.getIdeHome().resolve(IdeContext.FOLDER_UPDATES).resolve(IdeContext.FOLDER_VOLUME);
×
893
    mkdirs(mountPath);
×
894
    ProcessContext pc = this.context.newProcess();
×
895
    pc.executable("hdiutil");
×
896
    pc.addArgs("attach", "-quiet", "-nobrowse", "-mountpoint", mountPath, file);
×
897
    pc.run();
×
898
    Path appPath = findFirst(mountPath, p -> p.getFileName().toString().endsWith(".app"), false);
×
899
    if (appPath == null) {
×
900
      throw new IllegalStateException("Failed to unpack DMG as no MacOS *.app was found in file " + file);
×
901
    }
902

903
    copy(appPath, targetDir, FileCopyMode.COPY_TREE_OVERRIDE_TREE);
×
904
    pc.addArgs("detach", "-force", mountPath);
×
905
    pc.run();
×
906
  }
×
907

908
  @Override
909
  public void extractMsi(Path file, Path targetDir) {
910

911
    LOG.info("Extracting MSI file {} to {}", file, targetDir);
×
912
    this.context.newProcess().executable("msiexec").addArgs("/a", file, "/qn", "TARGETDIR=" + targetDir).run();
×
913
    // msiexec also creates a copy of the MSI
914
    Path msiCopy = targetDir.resolve(file.getFileName());
×
915
    delete(msiCopy);
×
916
  }
×
917

918
  @Override
919
  public void extractPkg(Path file, Path targetDir) {
920

921
    LOG.info("Extracting PKG file {} to {}", file, targetDir);
×
922
    Path tmpDirPkg = createTempDir("ide-pkg-");
×
923
    ProcessContext pc = this.context.newProcess();
×
924
    // we might also be able to use cpio from commons-compression instead of external xar...
925
    pc.executable("xar").addArgs("-C", tmpDirPkg, "-xf", file).run();
×
926
    Path contentPath = findFirst(tmpDirPkg, p -> p.getFileName().toString().equals("Payload"), true);
×
927
    extractTar(contentPath, targetDir, TarCompression.GZ);
×
928
    delete(tmpDirPkg);
×
929
  }
×
930

931
  @Override
932
  public void compress(Path dir, OutputStream out, String path) {
933

934
    String extension = FilenameUtil.getExtension(path);
3✔
935
    TarCompression tarCompression = TarCompression.of(extension);
3✔
936
    if (tarCompression != null) {
2!
937
      compressTar(dir, out, tarCompression);
6✔
938
    } else if (extension.equals("zip")) {
×
939
      compressZip(dir, out);
×
940
    } else {
941
      throw new IllegalArgumentException("Unsupported extension: " + extension);
×
942
    }
943
  }
1✔
944

945
  @Override
946
  public void compressTar(Path dir, OutputStream out, TarCompression tarCompression) {
947

948
    switch (tarCompression) {
8!
949
      case null -> compressTar(dir, out);
×
950
      case NONE -> compressTar(dir, out);
×
951
      case GZ -> compressTarGz(dir, out);
5✔
952
      case BZIP2 -> compressTarBzip2(dir, out);
×
953
      default -> throw new IllegalArgumentException("Unsupported tar compression: " + tarCompression);
×
954
    }
955
  }
1✔
956

957
  @Override
958
  public void compressTarGz(Path dir, OutputStream out) {
959

960
    try (GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(out)) {
5✔
961
      compressTarOrThrow(dir, gzOut);
4✔
962
    } catch (IOException e) {
×
963
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar.gz file.", e);
×
964
    }
1✔
965
  }
1✔
966

967
  @Override
968
  public void compressTarBzip2(Path dir, OutputStream out) {
969

970
    try (BZip2CompressorOutputStream bzip2Out = new BZip2CompressorOutputStream(out)) {
×
971
      compressTarOrThrow(dir, bzip2Out);
×
972
    } catch (IOException e) {
×
973
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar.bz2 file.", e);
×
974
    }
×
975
  }
×
976

977
  @Override
978
  public void compressTar(Path dir, OutputStream out) {
979

980
    try {
981
      compressTarOrThrow(dir, out);
×
982
    } catch (IOException e) {
×
983
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar file.", e);
×
984
    }
×
985
  }
×
986

987
  private void compressTarOrThrow(Path dir, OutputStream out) throws IOException {
988

989
    try (TarArchiveOutputStream tarOut = new TarArchiveOutputStream(out)) {
5✔
990
      compressRecursive(dir, tarOut, "");
5✔
991
      tarOut.finish();
2✔
992
    }
993
  }
1✔
994

995
  @Override
996
  public void compressZip(Path dir, OutputStream out) {
997

998
    try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(out)) {
×
999
      compressRecursive(dir, zipOut, "");
×
1000
      zipOut.finish();
×
1001
    } catch (IOException e) {
×
1002
      throw new IllegalStateException("Failed to compress directory " + dir + " to zip file.", e);
×
1003
    }
×
1004
  }
×
1005

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

1008
    try (Stream<Path> childStream = Files.list(path)) {
3✔
1009
      Iterator<Path> iterator = childStream.iterator();
3✔
1010
      while (iterator.hasNext()) {
3✔
1011
        Path child = iterator.next();
4✔
1012
        String relativeChildPath = relativePath + "/" + child.getFileName().toString();
6✔
1013
        boolean isDirectory = Files.isDirectory(child);
5✔
1014
        E archiveEntry = out.createArchiveEntry(child, relativeChildPath);
7✔
1015
        if (archiveEntry instanceof TarArchiveEntry tarEntry) {
6!
1016
          FileTime none = FileTime.fromMillis(0);
3✔
1017
          tarEntry.setCreationTime(none);
3✔
1018
          tarEntry.setModTime(none);
3✔
1019
          tarEntry.setLastAccessTime(none);
3✔
1020
          tarEntry.setLastModifiedTime(none);
3✔
1021
          tarEntry.setUserId(0);
3✔
1022
          tarEntry.setUserName("user");
3✔
1023
          tarEntry.setGroupId(0);
3✔
1024
          tarEntry.setGroupName("group");
3✔
1025
          PathPermissions filePermissions = getFilePermissions(child);
4✔
1026
          tarEntry.setMode(filePermissions.toMode());
4✔
1027
        }
1028
        out.putArchiveEntry(archiveEntry);
3✔
1029
        if (!isDirectory) {
2✔
1030
          try (InputStream in = Files.newInputStream(child)) {
5✔
1031
            IOUtils.copy(in, out);
4✔
1032
          }
1033
        }
1034
        out.closeArchiveEntry();
2✔
1035
        if (isDirectory) {
2✔
1036
          compressRecursive(child, out, relativeChildPath);
5✔
1037
        }
1038
      }
1✔
1039
    } catch (IOException e) {
×
1040
      throw new IllegalStateException("Failed to compress " + path, e);
×
1041
    }
1✔
1042
  }
1✔
1043

1044
  @Override
1045
  public void delete(Path path) {
1046

1047
    if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
9✔
1048
      LOG.trace("Deleting {} skipped as the path does not exist.", path);
4✔
1049
      return;
1✔
1050
    }
1051
    LOG.debug("Deleting {} ...", path);
4✔
1052
    try {
1053
      if (isDirectoryLink(path)) {
4✔
1054
        deletePath(path);
4✔
1055
      } else {
1056
        deleteRecursive(path);
3✔
1057
      }
1058
    } catch (IOException e) {
×
1059
      throw new IllegalStateException("Failed to delete " + path, e);
×
1060
    }
1✔
1061
  }
1✔
1062

1063
  private void deleteRecursive(Path path) throws IOException {
1064

1065
    if (Files.isSymbolicLink(path) || isJunction(path)) {
7!
1066
      LOG.trace("Deleting link {} ...", path);
4✔
1067
      Files.delete(path);
2✔
1068
      return;
1✔
1069
    }
1070
    if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) {
9✔
1071
      try (Stream<Path> childStream = Files.list(path)) {
3✔
1072
        Iterator<Path> iterator = childStream.iterator();
3✔
1073
        while (iterator.hasNext()) {
3✔
1074
          Path child = iterator.next();
4✔
1075
          deleteRecursive(child);
3✔
1076
        }
1✔
1077
      }
1078
    }
1079
    deletePath(path);
3✔
1080
  }
1✔
1081

1082
  private boolean isDirectoryLink(Path path) {
1083

1084
    return Files.isSymbolicLink(path) || isJunction(path);
11!
1085
  }
1086

1087
  private void deletePath(Path path) throws IOException {
1088

1089
    LOG.trace("Deleting {} ...", path);
4✔
1090
    boolean isSetWritable = setWritable(path, true);
5✔
1091
    if (!isSetWritable) {
2✔
1092
      LOG.debug("Couldn't give write access to file: {}", path);
4✔
1093
    }
1094
    Files.delete(path);
2✔
1095
  }
1✔
1096

1097
  @Override
1098
  public Path findFirst(Path dir, Predicate<Path> filter, boolean recursive) {
1099

1100
    try {
1101
      if (!Files.isDirectory(dir)) {
5!
1102
        return null;
×
1103
      }
1104
      return findFirstRecursive(dir, filter, recursive);
6✔
1105
    } catch (IOException e) {
×
1106
      throw new IllegalStateException("Failed to search for file in " + dir, e);
×
1107
    }
1108
  }
1109

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

1112
    List<Path> folders = null;
2✔
1113
    try (Stream<Path> childStream = Files.list(dir)) {
3✔
1114
      Iterator<Path> iterator = childStream.iterator();
3✔
1115
      while (iterator.hasNext()) {
3✔
1116
        Path child = iterator.next();
4✔
1117
        if (filter.test(child)) {
4✔
1118
          return child;
4✔
1119
        } else if (recursive && Files.isDirectory(child)) {
2!
1120
          if (folders == null) {
×
1121
            folders = new ArrayList<>();
×
1122
          }
1123
          folders.add(child);
×
1124
        }
1125
      }
1✔
1126
    }
4!
1127
    if (folders != null) {
2!
1128
      for (Path child : folders) {
×
1129
        Path match = findFirstRecursive(child, filter, recursive);
×
1130
        if (match != null) {
×
1131
          return match;
×
1132
        }
1133
      }
×
1134
    }
1135
    return null;
2✔
1136
  }
1137

1138
  @Override
1139
  public Path findAncestor(Path path, Path baseDir, int subfolderCount) {
1140

1141
    if ((path == null) || (baseDir == null)) {
4!
1142
      LOG.debug("Path should not be null for findAncestor.");
3✔
1143
      return null;
2✔
1144
    }
1145
    if (subfolderCount <= 0) {
2!
1146
      throw new IllegalArgumentException("Subfolder count: " + subfolderCount);
×
1147
    }
1148
    // 1. option relativize
1149
    // 2. recursive getParent
1150
    // 3. loop getParent???
1151
    // 4. getName + getNameCount
1152
    path = path.toAbsolutePath().normalize();
4✔
1153
    baseDir = baseDir.toAbsolutePath().normalize();
4✔
1154
    int directoryNameCount = path.getNameCount();
3✔
1155
    int baseDirNameCount = baseDir.getNameCount();
3✔
1156
    int delta = directoryNameCount - baseDirNameCount - subfolderCount;
6✔
1157
    if (delta < 0) {
2!
1158
      return null;
×
1159
    }
1160
    // ensure directory is a sub-folder of baseDir
1161
    for (int i = 0; i < baseDirNameCount; i++) {
7✔
1162
      if (!path.getName(i).toString().equals(baseDir.getName(i).toString())) {
10✔
1163
        return null;
2✔
1164
      }
1165
    }
1166
    Path result = path;
2✔
1167
    while (delta > 0) {
2✔
1168
      result = result.getParent();
3✔
1169
      delta--;
2✔
1170
    }
1171
    return result;
2✔
1172
  }
1173

1174
  @Override
1175
  public List<Path> listChildrenMapped(Path dir, Function<Path, Path> filter) {
1176

1177
    if (!Files.isDirectory(dir)) {
5✔
1178
      return List.of();
2✔
1179
    }
1180
    List<Path> children = new ArrayList<>();
4✔
1181
    try (Stream<Path> childStream = Files.list(dir)) {
3✔
1182
      Iterator<Path> iterator = childStream.iterator();
3✔
1183
      while (iterator.hasNext()) {
3✔
1184
        Path child = iterator.next();
4✔
1185
        Path filteredChild = filter.apply(child);
5✔
1186
        if (filteredChild != null) {
2✔
1187
          if (filteredChild == child) {
3!
1188
            LOG.trace("Accepted file {}", child);
5✔
1189
          } else {
1190
            LOG.trace("Accepted file {} and mapped to {}", child, filteredChild);
×
1191
          }
1192
          children.add(filteredChild);
5✔
1193
        } else {
1194
          LOG.trace("Ignoring file {} according to filter", child);
4✔
1195
        }
1196
      }
1✔
1197
    } catch (IOException e) {
×
1198
      throw new IllegalStateException("Failed to find children of directory " + dir, e);
×
1199
    }
1✔
1200
    return children;
2✔
1201
  }
1202

1203
  @Override
1204
  public boolean isEmptyDir(Path dir) {
1205

1206
    return listChildren(dir, f -> true).isEmpty();
8✔
1207
  }
1208

1209
  @Override
1210
  public boolean isNonEmptyFile(Path file) {
1211

1212
    if (Files.isRegularFile(file)) {
5✔
1213
      return (getFileSize(file) > 0);
10✔
1214
    }
1215
    return false;
2✔
1216
  }
1217

1218
  private long getFileSize(Path file) {
1219

1220
    try {
1221
      return Files.size(file);
3✔
1222
    } catch (IOException e) {
×
1223
      LOG.warn("Failed to determine size of file {}: {}", file, e.toString(), e);
×
1224
      return 0;
×
1225
    }
1226
  }
1227

1228
  private long getFileSizeRecursive(Path path) {
1229

1230
    long size = 0;
2✔
1231
    if (Files.isDirectory(path)) {
5✔
1232
      try (Stream<Path> childStream = Files.list(path)) {
3✔
1233
        Iterator<Path> iterator = childStream.iterator();
3✔
1234
        while (iterator.hasNext()) {
3✔
1235
          Path child = iterator.next();
4✔
1236
          size += getFileSizeRecursive(child);
6✔
1237
        }
1✔
1238
      } catch (IOException e) {
×
1239
        throw new RuntimeException("Failed to iterate children of folder " + path, e);
×
1240
      }
1✔
1241
    } else {
1242
      size += getFileSize(path);
6✔
1243
    }
1244
    return size;
2✔
1245
  }
1246

1247
  @Override
1248
  public Path findExistingFile(String fileName, List<Path> searchDirs) {
1249

1250
    for (Path dir : searchDirs) {
10!
1251
      Path filePath = dir.resolve(fileName);
4✔
1252
      try {
1253
        if (Files.exists(filePath)) {
5✔
1254
          return filePath;
2✔
1255
        }
1256
      } catch (Exception e) {
×
1257
        throw new IllegalStateException("Unexpected error while checking existence of file " + filePath + " .", e);
×
1258
      }
1✔
1259
    }
1✔
1260
    return null;
×
1261
  }
1262

1263
  @Override
1264
  public boolean setWritable(Path file, boolean writable) {
1265

1266
    if (!Files.exists(file)) {
5✔
1267
      return false;
2✔
1268
    }
1269
    try {
1270
      // POSIX
1271
      PosixFileAttributeView posix = Files.getFileAttributeView(file, PosixFileAttributeView.class);
7✔
1272
      if (posix != null) {
2!
1273
        Set<PosixFilePermission> permissions = new HashSet<>(posix.readAttributes().permissions());
7✔
1274
        boolean changed;
1275
        if (writable) {
2!
1276
          changed = permissions.add(PosixFilePermission.OWNER_WRITE);
5✔
1277
        } else {
1278
          changed = permissions.remove(PosixFilePermission.OWNER_WRITE);
×
1279
        }
1280
        if (changed) {
2!
1281
          posix.setPermissions(permissions);
×
1282
        }
1283
        return true;
2✔
1284
      }
1285

1286
      // Windows
1287
      DosFileAttributeView dos = Files.getFileAttributeView(file, DosFileAttributeView.class);
×
1288
      if (dos != null) {
×
1289
        dos.setReadOnly(!writable);
×
1290
        return true;
×
1291
      }
1292

1293
      LOG.debug("Failed to set writing permission for file {}", file);
×
1294
      return false;
×
1295

1296
    } catch (IOException e) {
×
1297
      LOG.debug("Error occurred when trying to set writing permission for file {}: {}", file, e.toString(), e);
×
1298
      return false;
×
1299
    }
1300
  }
1301

1302
  @Override
1303
  public void makeExecutable(Path path, boolean confirm) {
1304

1305
    if (Files.exists(path)) {
5✔
1306
      if (skipPermissionsIfWindows(path)) {
4!
1307
        return;
×
1308
      }
1309
      PathPermissions existingPermissions = getFilePermissions(path);
4✔
1310
      PathPermissions executablePermissions = existingPermissions.makeExecutable();
3✔
1311
      boolean update = (executablePermissions != existingPermissions);
7✔
1312
      if (update) {
2✔
1313
        if (confirm) {
2!
1314
          boolean yesContinue = this.context.question(
×
1315
              "We want to execute {} but this command seems to lack executable permissions!\n"
1316
                  + "Most probably the tool vendor did forget to add x-flags in the binary release package.\n"
1317
                  + "Before running the command, we suggest to set executable permissions to the file:\n"
1318
                  + "{}\n"
1319
                  + "For security reasons we ask for your confirmation so please check this request.\n"
1320
                  + "Changing permissions from {} to {}.\n"
1321
                  + "Do you confirm to make the command executable before running it?", path.getFileName(), path, existingPermissions, executablePermissions);
×
1322
          if (!yesContinue) {
×
1323
            return;
×
1324
          }
1325
        }
1326
        setFilePermissions(path, executablePermissions, false);
6✔
1327
      } else {
1328
        LOG.trace("Executable flags already present so no need to set them for file {}", path);
4✔
1329
      }
1330
    } else {
1✔
1331
      LOG.warn("Cannot set executable flag on file that does not exist: {}", path);
4✔
1332
    }
1333
  }
1✔
1334

1335
  @Override
1336
  public PathPermissions getFilePermissions(Path path) {
1337

1338
    PathPermissions pathPermissions;
1339
    String info = "";
2✔
1340
    if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
1341
      info = "mocked-";
×
1342
      if (Files.isDirectory(path)) {
×
1343
        pathPermissions = PathPermissions.MODE_RWX_RX_RX;
×
1344
      } else {
1345
        Path parent = path.getParent();
×
1346
        if ((parent != null) && (parent.getFileName().toString().equals("bin"))) {
×
1347
          pathPermissions = PathPermissions.MODE_RWX_RX_RX;
×
1348
        } else {
1349
          pathPermissions = PathPermissions.MODE_RW_R_R;
×
1350
        }
1351
      }
×
1352
    } else {
1353
      Set<PosixFilePermission> permissions;
1354
      try {
1355
        // Read the current file permissions
1356
        permissions = Files.getPosixFilePermissions(path);
5✔
1357
      } catch (IOException e) {
×
1358
        throw new RuntimeException("Failed to get permissions for " + path, e);
×
1359
      }
1✔
1360
      pathPermissions = PathPermissions.of(permissions);
3✔
1361
    }
1362
    LOG.trace("Read {}permissions of {} as {}.", info, path, pathPermissions);
17✔
1363
    return pathPermissions;
2✔
1364
  }
1365

1366
  @Override
1367
  public void setFilePermissions(Path path, PathPermissions permissions, boolean logErrorAndContinue) {
1368

1369
    if (skipPermissionsIfWindows(path)) {
4!
1370
      return;
×
1371
    }
1372
    try {
1373
      LOG.debug("Setting permissions for {} to {}", path, permissions);
5✔
1374
      // Set the new permissions
1375
      Files.setPosixFilePermissions(path, permissions.toPosix());
5✔
1376
    } catch (IOException e) {
×
1377
      String message = "Failed to set permissions to " + permissions + " for path " + path;
×
1378
      if (logErrorAndContinue) {
×
1379
        LOG.warn(message, e);
×
1380
      } else {
1381
        throw new RuntimeException(message, e);
×
1382
      }
1383
    }
1✔
1384
  }
1✔
1385

1386
  private boolean skipPermissionsIfWindows(Path path) {
1387

1388
    if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
1389
      LOG.trace("Windows does not have file permissions hence omitting for {}", path);
×
1390
      return true;
×
1391
    }
1392
    return false;
2✔
1393
  }
1394

1395
  @Override
1396
  public void touch(Path file) {
1397

1398
    if (Files.exists(file)) {
5✔
1399
      try {
1400
        Files.setLastModifiedTime(file, FileTime.fromMillis(System.currentTimeMillis()));
5✔
1401
      } catch (IOException e) {
×
1402
        throw new IllegalStateException("Could not update modification-time of " + file, e);
×
1403
      }
1✔
1404
    } else {
1405
      try {
1406
        Files.createFile(file);
5✔
1407
      } catch (IOException e) {
1✔
1408
        throw new IllegalStateException("Could not create empty file " + file, e);
8✔
1409
      }
1✔
1410
    }
1411
  }
1✔
1412

1413
  @Override
1414
  public String readFileContent(Path file) {
1415

1416
    LOG.trace("Reading content of file from {}", file);
4✔
1417
    if (!Files.exists((file))) {
5!
1418
      LOG.debug("File {} does not exist", file);
×
1419
      return null;
×
1420
    }
1421
    try {
1422
      String content = Files.readString(file);
3✔
1423
      LOG.trace("Completed reading {} character(s) from file {}", content.length(), file);
7✔
1424
      return content;
2✔
1425
    } catch (IOException e) {
×
1426
      throw new IllegalStateException("Failed to read file " + file, e);
×
1427
    }
1428
  }
1429

1430
  @Override
1431
  public void writeFileContent(String content, Path file, boolean createParentDir) {
1432

1433
    if (createParentDir) {
2✔
1434
      mkdirs(file.getParent());
4✔
1435
    }
1436
    if (content == null) {
2!
1437
      content = "";
×
1438
    }
1439
    LOG.trace("Writing content with {} character(s) to file {}", content.length(), file);
7✔
1440
    if (Files.exists(file)) {
5✔
1441
      LOG.info("Overriding content of file {}", file);
4✔
1442
    }
1443
    try {
1444
      Files.writeString(file, content);
6✔
1445
      LOG.trace("Wrote content to file {}", file);
4✔
1446
    } catch (IOException e) {
×
1447
      throw new RuntimeException("Failed to write file " + file, e);
×
1448
    }
1✔
1449
  }
1✔
1450

1451
  @Override
1452
  public List<String> readFileLines(Path file) {
1453

1454
    LOG.trace("Reading lines of file from {}", file);
4✔
1455
    if (!Files.exists(file)) {
5✔
1456
      LOG.warn("File {} does not exist", file);
4✔
1457
      return null;
2✔
1458
    }
1459
    try {
1460
      List<String> content = Files.readAllLines(file);
3✔
1461
      LOG.trace("Completed reading {} lines from file {}", content.size(), file);
7✔
1462
      return content;
2✔
1463
    } catch (IOException e) {
×
1464
      throw new IllegalStateException("Failed to read file " + file, e);
×
1465
    }
1466
  }
1467

1468
  @Override
1469
  public void writeFileLines(List<String> content, Path file, boolean createParentDir) {
1470

1471
    if (createParentDir) {
2!
1472
      mkdirs(file.getParent());
×
1473
    }
1474
    if (content == null) {
2!
1475
      content = List.of();
×
1476
    }
1477
    LOG.trace("Writing content with {} lines to file {}", content.size(), file);
7✔
1478
    if (Files.exists(file)) {
5✔
1479
      LOG.debug("Overriding content of file {}", file);
4✔
1480
    }
1481
    try {
1482
      Files.write(file, content);
6✔
1483
      LOG.trace("Wrote lines to file {}", file);
4✔
1484
    } catch (IOException e) {
×
1485
      throw new RuntimeException("Failed to write file " + file, e);
×
1486
    }
1✔
1487
  }
1✔
1488

1489
  @Override
1490
  public void readProperties(Path file, Properties properties) {
1491

1492
    try (Reader reader = Files.newBufferedReader(file)) {
3✔
1493
      properties.load(reader);
3✔
1494
      LOG.debug("Successfully loaded {} properties from {}", properties.size(), file);
7✔
1495
    } catch (IOException e) {
×
1496
      throw new IllegalStateException("Failed to read properties file: " + file, e);
×
1497
    }
1✔
1498
  }
1✔
1499

1500
  @Override
1501
  public void writeProperties(Properties properties, Path file, boolean createParentDir) {
1502

1503
    if (createParentDir) {
2✔
1504
      mkdirs(file.getParent());
4✔
1505
    }
1506
    try (Writer writer = Files.newBufferedWriter(file)) {
5✔
1507
      properties.store(writer, null); // do not get confused - Java still writes a date/time header that cannot be omitted
4✔
1508
      LOG.debug("Successfully saved {} properties to {}", properties.size(), file);
7✔
1509
    } catch (IOException e) {
×
1510
      throw new IllegalStateException("Failed to save properties file during tests.", e);
×
1511
    }
1✔
1512
  }
1✔
1513

1514
  @Override
1515
  public void readIniFile(Path file, IniFile iniFile) {
1516

1517
    if (!Files.exists(file)) {
5✔
1518
      LOG.debug("INI file {} does not exist.", iniFile);
4✔
1519
      return;
1✔
1520
    }
1521
    List<String> iniLines = readFileLines(file);
4✔
1522
    IniSection currentIniSection = iniFile.getInitialSection();
3✔
1523
    for (String line : iniLines) {
10✔
1524
      if (line.trim().startsWith("[")) {
5✔
1525
        currentIniSection = iniFile.getOrCreateSection(line);
5✔
1526
      } else if (line.isBlank() || IniComment.COMMENT_SYMBOLS.contains(line.trim().charAt(0))) {
11✔
1527
        currentIniSection.addComment(line);
4✔
1528
      } else {
1529
        int index = line.indexOf('=');
4✔
1530
        if (index > 0) {
2!
1531
          currentIniSection.setProperty(line);
3✔
1532
        }
1533
      }
1534
    }
1✔
1535
  }
1✔
1536

1537
  @Override
1538
  public void writeIniFile(IniFile iniFile, Path file, boolean createParentDir) {
1539

1540
    String iniString = iniFile.toString();
3✔
1541
    writeFileContent(iniString, file, createParentDir);
5✔
1542
  }
1✔
1543

1544
  @Override
1545
  public Duration getFileAge(Path path) {
1546

1547
    if (Files.exists(path)) {
5✔
1548
      try {
1549
        long currentTime = System.currentTimeMillis();
2✔
1550
        long fileModifiedTime = Files.getLastModifiedTime(path).toMillis();
6✔
1551
        return Duration.ofMillis(currentTime - fileModifiedTime);
5✔
1552
      } catch (IOException e) {
×
1553
        LOG.warn("Could not get modification-time of {}.", path, e);
×
1554
      }
×
1555
    } else {
1556
      LOG.debug("Path {} is missing - skipping modification-time and file age check.", path);
4✔
1557
    }
1558
    return null;
2✔
1559
  }
1560

1561
  @Override
1562
  public boolean isFileAgeRecent(Path path, Duration cacheDuration) {
1563

1564
    Duration age = getFileAge(path);
4✔
1565
    if (age == null) {
2✔
1566
      return false;
2✔
1567
    }
1568
    LOG.debug("The path {} was last updated {} ago and caching duration is {}.", path, age, cacheDuration);
17✔
1569
    return (age.toMillis() <= cacheDuration.toMillis());
10✔
1570
  }
1571
}
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