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

devonfw / IDEasy / 23046287511

13 Mar 2026 10:16AM UTC coverage: 70.609% (+0.01%) from 70.598%
23046287511

push

github

web-flow
#1743: fixed mklink creation (#1744)

4141 of 6462 branches covered (64.08%)

Branch coverage included in aggregate %.

10747 of 14623 relevant lines covered (73.49%)

3.09 hits per line

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

67.63
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
    LOG.trace("Creating a Windows {} at {} pointing to {}", type, link, source);
×
489
    ProcessContext pc = this.context.newProcess().executable("cmd").addArgs("/c", "mklink", type.getMklinkOption());
×
490
    Path finalSource = source;
×
491
    Path finalLink = link;
×
492
    if (relative) {
×
493
      int count = getCommonNameCount(source, link);
×
494
      if (count < 1) {
×
495
        LOG.error("Cannot create relative link at {} pointing to {} - falling back to absolute link", link, source);
×
496
      } else {
497
        Path cwd = getPathStart(source, count - 1);
×
498
        finalSource = getPathEnd(source, count);
×
499
        finalLink = getPathEnd(link, count);
×
500
        pc.directory(cwd);
×
501
      }
502
    }
503
    if (type == PathLinkType.SYMBOLIC_LINK && Files.isDirectory(source)) {
×
504
      pc = pc.addArg("/j");
×
505
    }
506
    pc = pc.addArgs(finalLink.toString(), finalSource.toString());
×
507
    ProcessResult result = pc.run(ProcessMode.DEFAULT);
×
508
    result.failOnError();
×
509
  }
×
510

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

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

547
  @Override
548
  public Path getPathStart(Path path, int nameEnd) {
549

550
    int count = path.getNameCount();
3✔
551
    int delta = count - nameEnd - 1;
6✔
552
    if (delta < 0) {
2!
553
      throw new IllegalArgumentException("Cannot get start before segment " + nameEnd + " from path " + path + " that has only " + count + " segments.");
×
554
    }
555
    Path result = path;
2✔
556
    while (delta > 0) {
2✔
557
      result = result.getParent();
3✔
558
      delta--;
2✔
559
    }
560
    return result;
2✔
561
  }
562

563
  @Override
564
  public Path getPathEnd(Path path, int nameStart) {
565

566
    int count = path.getNameCount();
3✔
567
    if (nameStart > count) {
3!
568
      throw new IllegalArgumentException("Cannot get end after segment " + nameStart + " from path " + path + " that has only " + count + " segments.");
×
569
    } else if (nameStart == count) {
3!
570
      return Path.of(".");
×
571
    }
572
    Path result = path.getName(nameStart++);
5✔
573
    while (nameStart < count) {
3✔
574
      result = result.resolve(path.getName(nameStart++));
8✔
575
    }
576
    return result;
2✔
577
  }
578

579
  @Override
580
  public int getCommonNameCount(Path path1, Path path2) {
581

582
    if ((path1 == null) || (path2 == null) || !Objects.equals(path1.getRoot(), path2.getRoot())) {
10✔
583
      return -1;
2✔
584
    }
585
    int minNameCount = Math.min(path1.getNameCount(), path2.getNameCount());
6✔
586
    int i = 0;
2✔
587
    while (i < minNameCount) {
3!
588
      Path segment1 = path1.getName(i);
4✔
589
      Path segment2 = path2.getName(i);
4✔
590
      if (!segment1.equals(segment2)) {
4✔
591
        break;
1✔
592
      }
593
      i++;
1✔
594
    }
1✔
595
    return i;
2✔
596
  }
597

598
  @Override
599
  public Path toRealPath(Path path) {
600

601
    return toRealPath(path, true);
5✔
602
  }
603

604
  @Override
605
  public Path toCanonicalPath(Path path) {
606

607
    return toRealPath(path, false);
5✔
608
  }
609

610
  private Path toRealPath(Path path, boolean resolveLinks) {
611

612
    try {
613
      Path realPath;
614
      if (resolveLinks) {
2✔
615
        realPath = path.toRealPath();
6✔
616
      } else {
617
        realPath = path.toRealPath(LinkOption.NOFOLLOW_LINKS);
9✔
618
      }
619
      if (!realPath.equals(path)) {
4✔
620
        LOG.trace("Resolved path {} to {}", path, realPath);
5✔
621
      }
622
      return realPath;
2✔
623
    } catch (IOException e) {
×
624
      throw new IllegalStateException("Failed to get real path for " + path, e);
×
625
    }
626
  }
627

628
  @Override
629
  public Path createTempDir(String name) {
630

631
    try {
632
      Path tmp = this.context.getTempPath();
4✔
633
      Path tempDir = tmp.resolve(name);
4✔
634
      int tries = 1;
2✔
635
      while (Files.exists(tempDir)) {
5!
636
        long id = System.nanoTime() & 0xFFFF;
×
637
        tempDir = tmp.resolve(name + "-" + id);
×
638
        tries++;
×
639
        if (tries > 200) {
×
640
          throw new IOException("Unable to create unique name!");
×
641
        }
642
      }
×
643
      return Files.createDirectory(tempDir);
5✔
644
    } catch (IOException e) {
×
645
      throw new IllegalStateException("Failed to create temporary directory with prefix '" + name + "'!", e);
×
646
    }
647
  }
648

649
  @Override
650
  public void extract(Path archiveFile, Path targetDir, Consumer<Path> postExtractHook, boolean extract) {
651

652
    if (Files.isDirectory(archiveFile)) {
5✔
653
      LOG.warn("Found directory for download at {} hence copying without extraction!", archiveFile);
4✔
654
      copy(archiveFile, targetDir, FileCopyMode.COPY_TREE_CONTENT);
5✔
655
      postExtractHook(postExtractHook, targetDir);
4✔
656
      return;
1✔
657
    } else if (!extract) {
2✔
658
      mkdirs(targetDir);
3✔
659
      move(archiveFile, targetDir.resolve(archiveFile.getFileName()));
9✔
660
      return;
1✔
661
    }
662
    Path tmpDir = createTempDir("extract-" + archiveFile.getFileName());
7✔
663
    LOG.trace("Trying to extract the file {} to {} and move it to {}.", archiveFile, tmpDir, targetDir);
17✔
664
    String filename = archiveFile.getFileName().toString();
4✔
665
    TarCompression tarCompression = TarCompression.of(filename);
3✔
666
    if (tarCompression != null) {
2✔
667
      extractTar(archiveFile, tmpDir, tarCompression);
6✔
668
    } else {
669
      String extension = FilenameUtil.getExtension(filename);
3✔
670
      if (extension == null) {
2!
671
        throw new IllegalStateException("Unknown archive format without extension - can not extract " + archiveFile);
×
672
      } else {
673
        LOG.trace("Determined file extension {}", extension);
4✔
674
      }
675
      switch (extension) {
8!
676
        case "zip" -> extractZip(archiveFile, tmpDir);
×
677
        case "jar" -> extractJar(archiveFile, tmpDir);
5✔
678
        case "dmg" -> extractDmg(archiveFile, tmpDir);
×
679
        case "msi" -> extractMsi(archiveFile, tmpDir);
×
680
        case "pkg" -> extractPkg(archiveFile, tmpDir);
×
681
        default -> throw new IllegalStateException("Unknown archive format " + extension + ". Can not extract " + archiveFile);
×
682
      }
683
    }
684
    Path properInstallDir = getProperInstallationSubDirOf(tmpDir, archiveFile);
5✔
685
    postExtractHook(postExtractHook, properInstallDir);
4✔
686
    move(properInstallDir, targetDir);
6✔
687
    delete(tmpDir);
3✔
688
  }
1✔
689

690
  private void postExtractHook(Consumer<Path> postExtractHook, Path properInstallDir) {
691

692
    if (postExtractHook != null) {
2✔
693
      postExtractHook.accept(properInstallDir);
3✔
694
    }
695
  }
1✔
696

697
  /**
698
   * @param path the {@link Path} to start the recursive search from.
699
   * @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
700
   *     item in their respective directory and {@code s} is not named "bin".
701
   */
702
  private Path getProperInstallationSubDirOf(Path path, Path archiveFile) {
703

704
    try (Stream<Path> stream = Files.list(path)) {
3✔
705
      Path[] subFiles = stream.toArray(Path[]::new);
8✔
706
      if (subFiles.length == 0) {
3!
707
        throw new CliException("The downloaded package " + archiveFile + " seems to be empty as you can check in the extracted folder " + path);
×
708
      } else if (subFiles.length == 1) {
4✔
709
        String filename = subFiles[0].getFileName().toString();
6✔
710
        if (!filename.equals(IdeContext.FOLDER_BIN) && !filename.equals(IdeContext.FOLDER_CONTENTS) && !filename.endsWith(".app") && Files.isDirectory(
19!
711
            subFiles[0])) {
712
          return getProperInstallationSubDirOf(subFiles[0], archiveFile);
9✔
713
        }
714
      }
715
      return path;
4✔
716
    } catch (IOException e) {
4!
717
      throw new IllegalStateException("Failed to get sub-files of " + path);
×
718
    }
719
  }
720

721
  @Override
722
  public void extractZip(Path file, Path targetDir) {
723

724
    LOG.info("Extracting ZIP file {} to {}", file, targetDir);
5✔
725
    URI uri = URI.create("jar:" + file.toUri());
6✔
726
    try (FileSystem fs = FileSystems.newFileSystem(uri, FS_ENV)) {
4✔
727
      long size = 0;
2✔
728
      for (Path root : fs.getRootDirectories()) {
11✔
729
        size += getFileSizeRecursive(root);
6✔
730
      }
1✔
731
      try (final IdeProgressBar progressBar = this.context.newProgressbarForExtracting(size)) {
5✔
732
        for (Path root : fs.getRootDirectories()) {
11✔
733
          copy(root, targetDir, FileCopyMode.EXTRACT, (s, t, d) -> onFileCopiedFromZip(s, t, d, progressBar));
15✔
734
        }
1✔
735
      }
736
    } catch (IOException e) {
×
737
      throw new IllegalStateException("Failed to extract " + file + " to " + targetDir, e);
×
738
    }
1✔
739
  }
1✔
740

741
  @SuppressWarnings("unchecked")
742
  private void onFileCopiedFromZip(Path source, Path target, boolean directory, IdeProgressBar progressBar) {
743

744
    if (directory) {
2✔
745
      return;
1✔
746
    }
747
    if (!this.context.getSystemInfo().isWindows()) {
5✔
748
      try {
749
        Object attribute = Files.getAttribute(source, "zip:permissions");
6✔
750
        if (attribute instanceof Set<?> permissionSet) {
6✔
751
          Files.setPosixFilePermissions(target, (Set<PosixFilePermission>) permissionSet);
4✔
752
        }
753
      } catch (Exception e) {
×
754
        LOG.error("Failed to transfer zip permissions for {}", target, e);
×
755
      }
1✔
756
    }
757
    progressBar.stepBy(getFileSize(target));
5✔
758
  }
1✔
759

760
  @Override
761
  public void extractTar(Path file, Path targetDir, TarCompression compression) {
762

763
    extractArchive(file, targetDir, in -> new TarArchiveInputStream(compression.unpack(in)));
13✔
764
  }
1✔
765

766
  @Override
767
  public void extractJar(Path file, Path targetDir) {
768

769
    extractZip(file, targetDir);
4✔
770
  }
1✔
771

772
  /**
773
   * @param permissions The integer as returned by {@link TarArchiveEntry#getMode()} that represents the file permissions of a file on a Unix file system.
774
   * @return A String representing the file permissions. E.g. "rwxrwxr-x" or "rw-rw-r--"
775
   */
776
  public static String generatePermissionString(int permissions) {
777

778
    // Ensure that only the last 9 bits are considered
779
    permissions &= 0b111111111;
4✔
780

781
    StringBuilder permissionStringBuilder = new StringBuilder("rwxrwxrwx");
5✔
782
    for (int i = 0; i < 9; i++) {
7✔
783
      int mask = 1 << i;
4✔
784
      char currentChar = ((permissions & mask) != 0) ? permissionStringBuilder.charAt(8 - i) : '-';
12✔
785
      permissionStringBuilder.setCharAt(8 - i, currentChar);
6✔
786
    }
787

788
    return permissionStringBuilder.toString();
3✔
789
  }
790

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

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

795
    final List<PathLink> links = new ArrayList<>();
4✔
796
    try (InputStream is = Files.newInputStream(file);
5✔
797
        ArchiveInputStream<?> ais = unpacker.apply(is);
5✔
798
        IdeProgressBar pb = this.context.newProgressbarForExtracting(getFileSize(file))) {
7✔
799

800
      final Path root = targetDir.toAbsolutePath().normalize();
4✔
801

802
      ArchiveEntry entry = ais.getNextEntry();
3✔
803
      while (entry != null) {
2✔
804
        String entryName = entry.getName();
3✔
805
        Path entryPath = resolveRelativePathSecure(entryName, root);
5✔
806
        PathPermissions permissions = null;
2✔
807
        PathLinkType linkType = null;
2✔
808
        if (entry instanceof TarArchiveEntry tae) {
6!
809
          if (tae.isSymbolicLink()) {
3✔
810
            linkType = PathLinkType.SYMBOLIC_LINK;
3✔
811
          } else if (tae.isLink()) {
3!
812
            linkType = PathLinkType.HARD_LINK;
×
813
          }
814
          if (linkType == null) {
2✔
815
            permissions = PathPermissions.of(tae.getMode());
5✔
816
          } else {
817
            Path parent = entryPath.getParent();
3✔
818
            String sourcePathString = tae.getLinkName();
3✔
819
            Path source = parent.resolve(sourcePathString).normalize();
5✔
820
            source = resolveRelativePathSecure(source, root, sourcePathString);
6✔
821
            links.add(new PathLink(source, entryPath, linkType));
9✔
822
            mkdirs(parent);
3✔
823
          }
824
        }
825
        if (entry.isDirectory()) {
3✔
826
          mkdirs(entryPath);
4✔
827
        } else if (linkType == null) { // regular file
2✔
828
          mkdirs(entryPath.getParent());
4✔
829
          Files.copy(ais, entryPath, StandardCopyOption.REPLACE_EXISTING);
10✔
830
          // POSIX perms on non-Windows
831
          if (permissions != null) {
2!
832
            setFilePermissions(entryPath, permissions, false);
5✔
833
          }
834
        }
835
        pb.stepBy(Math.max(0L, entry.getSize()));
6✔
836
        entry = ais.getNextEntry();
3✔
837
      }
1✔
838
      // post process links
839
      for (PathLink link : links) {
10✔
840
        link(link);
3✔
841
      }
1✔
842
    } catch (Exception e) {
×
843
      throw new IllegalStateException("Failed to extract " + file + " to " + targetDir, e);
×
844
    }
1✔
845
  }
1✔
846

847
  private Path resolveRelativePathSecure(String entryName, Path root) {
848

849
    Path entryPath = root.resolve(entryName).normalize();
5✔
850
    return resolveRelativePathSecure(entryPath, root, entryName);
6✔
851
  }
852

853
  private Path resolveRelativePathSecure(Path entryPath, Path root, String entryName) {
854

855
    if (!entryPath.startsWith(root)) {
4!
856
      throw new IllegalStateException("Preventing path traversal attack from " + entryName + " to " + entryPath + " leaving " + root);
×
857
    }
858
    return entryPath;
2✔
859
  }
860

861
  @Override
862
  public void extractDmg(Path file, Path targetDir) {
863

864
    LOG.info("Extracting DMG file {} to {}", file, targetDir);
×
865
    assert this.context.getSystemInfo().isMac();
×
866

867
    Path mountPath = this.context.getIdeHome().resolve(IdeContext.FOLDER_UPDATES).resolve(IdeContext.FOLDER_VOLUME);
×
868
    mkdirs(mountPath);
×
869
    ProcessContext pc = this.context.newProcess();
×
870
    pc.executable("hdiutil");
×
871
    pc.addArgs("attach", "-quiet", "-nobrowse", "-mountpoint", mountPath, file);
×
872
    pc.run();
×
873
    Path appPath = findFirst(mountPath, p -> p.getFileName().toString().endsWith(".app"), false);
×
874
    if (appPath == null) {
×
875
      throw new IllegalStateException("Failed to unpack DMG as no MacOS *.app was found in file " + file);
×
876
    }
877

878
    copy(appPath, targetDir, FileCopyMode.COPY_TREE_OVERRIDE_TREE);
×
879
    pc.addArgs("detach", "-force", mountPath);
×
880
    pc.run();
×
881
  }
×
882

883
  @Override
884
  public void extractMsi(Path file, Path targetDir) {
885

886
    LOG.info("Extracting MSI file {} to {}", file, targetDir);
×
887
    this.context.newProcess().executable("msiexec").addArgs("/a", file, "/qn", "TARGETDIR=" + targetDir).run();
×
888
    // msiexec also creates a copy of the MSI
889
    Path msiCopy = targetDir.resolve(file.getFileName());
×
890
    delete(msiCopy);
×
891
  }
×
892

893
  @Override
894
  public void extractPkg(Path file, Path targetDir) {
895

896
    LOG.info("Extracting PKG file {} to {}", file, targetDir);
×
897
    Path tmpDirPkg = createTempDir("ide-pkg-");
×
898
    ProcessContext pc = this.context.newProcess();
×
899
    // we might also be able to use cpio from commons-compression instead of external xar...
900
    pc.executable("xar").addArgs("-C", tmpDirPkg, "-xf", file).run();
×
901
    Path contentPath = findFirst(tmpDirPkg, p -> p.getFileName().toString().equals("Payload"), true);
×
902
    extractTar(contentPath, targetDir, TarCompression.GZ);
×
903
    delete(tmpDirPkg);
×
904
  }
×
905

906
  @Override
907
  public void compress(Path dir, OutputStream out, String path) {
908

909
    String extension = FilenameUtil.getExtension(path);
3✔
910
    TarCompression tarCompression = TarCompression.of(extension);
3✔
911
    if (tarCompression != null) {
2!
912
      compressTar(dir, out, tarCompression);
6✔
913
    } else if (extension.equals("zip")) {
×
914
      compressZip(dir, out);
×
915
    } else {
916
      throw new IllegalArgumentException("Unsupported extension: " + extension);
×
917
    }
918
  }
1✔
919

920
  @Override
921
  public void compressTar(Path dir, OutputStream out, TarCompression tarCompression) {
922

923
    switch (tarCompression) {
8!
924
      case null -> compressTar(dir, out);
×
925
      case NONE -> compressTar(dir, out);
×
926
      case GZ -> compressTarGz(dir, out);
5✔
927
      case BZIP2 -> compressTarBzip2(dir, out);
×
928
      default -> throw new IllegalArgumentException("Unsupported tar compression: " + tarCompression);
×
929
    }
930
  }
1✔
931

932
  @Override
933
  public void compressTarGz(Path dir, OutputStream out) {
934

935
    try (GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(out)) {
5✔
936
      compressTarOrThrow(dir, gzOut);
4✔
937
    } catch (IOException e) {
×
938
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar.gz file.", e);
×
939
    }
1✔
940
  }
1✔
941

942
  @Override
943
  public void compressTarBzip2(Path dir, OutputStream out) {
944

945
    try (BZip2CompressorOutputStream bzip2Out = new BZip2CompressorOutputStream(out)) {
×
946
      compressTarOrThrow(dir, bzip2Out);
×
947
    } catch (IOException e) {
×
948
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar.bz2 file.", e);
×
949
    }
×
950
  }
×
951

952
  @Override
953
  public void compressTar(Path dir, OutputStream out) {
954

955
    try {
956
      compressTarOrThrow(dir, out);
×
957
    } catch (IOException e) {
×
958
      throw new IllegalStateException("Failed to compress directory " + dir + " to tar file.", e);
×
959
    }
×
960
  }
×
961

962
  private void compressTarOrThrow(Path dir, OutputStream out) throws IOException {
963

964
    try (TarArchiveOutputStream tarOut = new TarArchiveOutputStream(out)) {
5✔
965
      compressRecursive(dir, tarOut, "");
5✔
966
      tarOut.finish();
2✔
967
    }
968
  }
1✔
969

970
  @Override
971
  public void compressZip(Path dir, OutputStream out) {
972

973
    try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(out)) {
×
974
      compressRecursive(dir, zipOut, "");
×
975
      zipOut.finish();
×
976
    } catch (IOException e) {
×
977
      throw new IllegalStateException("Failed to compress directory " + dir + " to zip file.", e);
×
978
    }
×
979
  }
×
980

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

983
    try (Stream<Path> childStream = Files.list(path)) {
3✔
984
      Iterator<Path> iterator = childStream.iterator();
3✔
985
      while (iterator.hasNext()) {
3✔
986
        Path child = iterator.next();
4✔
987
        String relativeChildPath = relativePath + "/" + child.getFileName().toString();
6✔
988
        boolean isDirectory = Files.isDirectory(child);
5✔
989
        E archiveEntry = out.createArchiveEntry(child, relativeChildPath);
7✔
990
        if (archiveEntry instanceof TarArchiveEntry tarEntry) {
6!
991
          FileTime none = FileTime.fromMillis(0);
3✔
992
          tarEntry.setCreationTime(none);
3✔
993
          tarEntry.setModTime(none);
3✔
994
          tarEntry.setLastAccessTime(none);
3✔
995
          tarEntry.setLastModifiedTime(none);
3✔
996
          tarEntry.setUserId(0);
3✔
997
          tarEntry.setUserName("user");
3✔
998
          tarEntry.setGroupId(0);
3✔
999
          tarEntry.setGroupName("group");
3✔
1000
          PathPermissions filePermissions = getFilePermissions(child);
4✔
1001
          tarEntry.setMode(filePermissions.toMode());
4✔
1002
        }
1003
        out.putArchiveEntry(archiveEntry);
3✔
1004
        if (!isDirectory) {
2✔
1005
          try (InputStream in = Files.newInputStream(child)) {
5✔
1006
            IOUtils.copy(in, out);
4✔
1007
          }
1008
        }
1009
        out.closeArchiveEntry();
2✔
1010
        if (isDirectory) {
2✔
1011
          compressRecursive(child, out, relativeChildPath);
5✔
1012
        }
1013
      }
1✔
1014
    } catch (IOException e) {
×
1015
      throw new IllegalStateException("Failed to compress " + path, e);
×
1016
    }
1✔
1017
  }
1✔
1018

1019
  @Override
1020
  public void delete(Path path) {
1021

1022
    if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
9✔
1023
      LOG.trace("Deleting {} skipped as the path does not exist.", path);
4✔
1024
      return;
1✔
1025
    }
1026
    LOG.debug("Deleting {} ...", path);
4✔
1027
    try {
1028
      if (Files.isSymbolicLink(path) || isJunction(path)) {
7!
1029
        Files.delete(path);
3✔
1030
      } else {
1031
        deleteRecursive(path);
3✔
1032
      }
1033
    } catch (IOException e) {
×
1034
      throw new IllegalStateException("Failed to delete " + path, e);
×
1035
    }
1✔
1036
  }
1✔
1037

1038
  private void deleteRecursive(Path path) throws IOException {
1039

1040
    if (Files.isDirectory(path)) {
5✔
1041
      try (Stream<Path> childStream = Files.list(path)) {
3✔
1042
        Iterator<Path> iterator = childStream.iterator();
3✔
1043
        while (iterator.hasNext()) {
3✔
1044
          Path child = iterator.next();
4✔
1045
          deleteRecursive(child);
3✔
1046
        }
1✔
1047
      }
1048
    }
1049
    LOG.trace("Deleting {} ...", path);
4✔
1050
    boolean isSetWritable = setWritable(path, true);
5✔
1051
    if (!isSetWritable) {
2✔
1052
      LOG.debug("Couldn't give write access to file: {}", path);
4✔
1053
    }
1054
    Files.delete(path);
2✔
1055
  }
1✔
1056

1057
  @Override
1058
  public Path findFirst(Path dir, Predicate<Path> filter, boolean recursive) {
1059

1060
    try {
1061
      if (!Files.isDirectory(dir)) {
5!
1062
        return null;
×
1063
      }
1064
      return findFirstRecursive(dir, filter, recursive);
6✔
1065
    } catch (IOException e) {
×
1066
      throw new IllegalStateException("Failed to search for file in " + dir, e);
×
1067
    }
1068
  }
1069

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

1072
    List<Path> folders = null;
2✔
1073
    try (Stream<Path> childStream = Files.list(dir)) {
3✔
1074
      Iterator<Path> iterator = childStream.iterator();
3✔
1075
      while (iterator.hasNext()) {
3✔
1076
        Path child = iterator.next();
4✔
1077
        if (filter.test(child)) {
4✔
1078
          return child;
4✔
1079
        } else if (recursive && Files.isDirectory(child)) {
2!
1080
          if (folders == null) {
×
1081
            folders = new ArrayList<>();
×
1082
          }
1083
          folders.add(child);
×
1084
        }
1085
      }
1✔
1086
    }
4!
1087
    if (folders != null) {
2!
1088
      for (Path child : folders) {
×
1089
        Path match = findFirstRecursive(child, filter, recursive);
×
1090
        if (match != null) {
×
1091
          return match;
×
1092
        }
1093
      }
×
1094
    }
1095
    return null;
2✔
1096
  }
1097

1098
  @Override
1099
  public Path findAncestor(Path path, Path baseDir, int subfolderCount) {
1100

1101
    if ((path == null) || (baseDir == null)) {
4!
1102
      LOG.debug("Path should not be null for findAncestor.");
3✔
1103
      return null;
2✔
1104
    }
1105
    if (subfolderCount <= 0) {
2!
1106
      throw new IllegalArgumentException("Subfolder count: " + subfolderCount);
×
1107
    }
1108
    // 1. option relativize
1109
    // 2. recursive getParent
1110
    // 3. loop getParent???
1111
    // 4. getName + getNameCount
1112
    path = path.toAbsolutePath().normalize();
4✔
1113
    baseDir = baseDir.toAbsolutePath().normalize();
4✔
1114
    int directoryNameCount = path.getNameCount();
3✔
1115
    int baseDirNameCount = baseDir.getNameCount();
3✔
1116
    int delta = directoryNameCount - baseDirNameCount - subfolderCount;
6✔
1117
    if (delta < 0) {
2!
1118
      return null;
×
1119
    }
1120
    // ensure directory is a sub-folder of baseDir
1121
    for (int i = 0; i < baseDirNameCount; i++) {
7✔
1122
      if (!path.getName(i).toString().equals(baseDir.getName(i).toString())) {
10✔
1123
        return null;
2✔
1124
      }
1125
    }
1126
    Path result = path;
2✔
1127
    while (delta > 0) {
2✔
1128
      result = result.getParent();
3✔
1129
      delta--;
2✔
1130
    }
1131
    return result;
2✔
1132
  }
1133

1134
  @Override
1135
  public List<Path> listChildrenMapped(Path dir, Function<Path, Path> filter) {
1136

1137
    if (!Files.isDirectory(dir)) {
5✔
1138
      return List.of();
2✔
1139
    }
1140
    List<Path> children = new ArrayList<>();
4✔
1141
    try (Stream<Path> childStream = Files.list(dir)) {
3✔
1142
      Iterator<Path> iterator = childStream.iterator();
3✔
1143
      while (iterator.hasNext()) {
3✔
1144
        Path child = iterator.next();
4✔
1145
        Path filteredChild = filter.apply(child);
5✔
1146
        if (filteredChild != null) {
2✔
1147
          if (filteredChild == child) {
3!
1148
            LOG.trace("Accepted file {}", child);
5✔
1149
          } else {
1150
            LOG.trace("Accepted file {} and mapped to {}", child, filteredChild);
×
1151
          }
1152
          children.add(filteredChild);
5✔
1153
        } else {
1154
          LOG.trace("Ignoring file {} according to filter", child);
4✔
1155
        }
1156
      }
1✔
1157
    } catch (IOException e) {
×
1158
      throw new IllegalStateException("Failed to find children of directory " + dir, e);
×
1159
    }
1✔
1160
    return children;
2✔
1161
  }
1162

1163
  @Override
1164
  public boolean isEmptyDir(Path dir) {
1165

1166
    return listChildren(dir, f -> true).isEmpty();
8✔
1167
  }
1168

1169
  @Override
1170
  public boolean isNonEmptyFile(Path file) {
1171

1172
    if (Files.isRegularFile(file)) {
5✔
1173
      return (getFileSize(file) > 0);
10✔
1174
    }
1175
    return false;
2✔
1176
  }
1177

1178
  private long getFileSize(Path file) {
1179

1180
    try {
1181
      return Files.size(file);
3✔
1182
    } catch (IOException e) {
×
1183
      LOG.warn("Failed to determine size of file {}: {}", file, e.toString(), e);
×
1184
      return 0;
×
1185
    }
1186
  }
1187

1188
  private long getFileSizeRecursive(Path path) {
1189

1190
    long size = 0;
2✔
1191
    if (Files.isDirectory(path)) {
5✔
1192
      try (Stream<Path> childStream = Files.list(path)) {
3✔
1193
        Iterator<Path> iterator = childStream.iterator();
3✔
1194
        while (iterator.hasNext()) {
3✔
1195
          Path child = iterator.next();
4✔
1196
          size += getFileSizeRecursive(child);
6✔
1197
        }
1✔
1198
      } catch (IOException e) {
×
1199
        throw new RuntimeException("Failed to iterate children of folder " + path, e);
×
1200
      }
1✔
1201
    } else {
1202
      size += getFileSize(path);
6✔
1203
    }
1204
    return size;
2✔
1205
  }
1206

1207
  @Override
1208
  public Path findExistingFile(String fileName, List<Path> searchDirs) {
1209

1210
    for (Path dir : searchDirs) {
10!
1211
      Path filePath = dir.resolve(fileName);
4✔
1212
      try {
1213
        if (Files.exists(filePath)) {
5✔
1214
          return filePath;
2✔
1215
        }
1216
      } catch (Exception e) {
×
1217
        throw new IllegalStateException("Unexpected error while checking existence of file " + filePath + " .", e);
×
1218
      }
1✔
1219
    }
1✔
1220
    return null;
×
1221
  }
1222

1223
  @Override
1224
  public boolean setWritable(Path file, boolean writable) {
1225

1226
    if (!Files.exists(file)) {
5✔
1227
      return false;
2✔
1228
    }
1229
    try {
1230
      // POSIX
1231
      PosixFileAttributeView posix = Files.getFileAttributeView(file, PosixFileAttributeView.class);
7✔
1232
      if (posix != null) {
2!
1233
        Set<PosixFilePermission> permissions = new HashSet<>(posix.readAttributes().permissions());
7✔
1234
        boolean changed;
1235
        if (writable) {
2!
1236
          changed = permissions.add(PosixFilePermission.OWNER_WRITE);
5✔
1237
        } else {
1238
          changed = permissions.remove(PosixFilePermission.OWNER_WRITE);
×
1239
        }
1240
        if (changed) {
2!
1241
          posix.setPermissions(permissions);
×
1242
        }
1243
        return true;
2✔
1244
      }
1245

1246
      // Windows
1247
      DosFileAttributeView dos = Files.getFileAttributeView(file, DosFileAttributeView.class);
×
1248
      if (dos != null) {
×
1249
        dos.setReadOnly(!writable);
×
1250
        return true;
×
1251
      }
1252

1253
      LOG.debug("Failed to set writing permission for file {}", file);
×
1254
      return false;
×
1255

1256
    } catch (IOException e) {
×
1257
      LOG.debug("Error occurred when trying to set writing permission for file {}: {}", file, e.toString(), e);
×
1258
      return false;
×
1259
    }
1260
  }
1261

1262
  @Override
1263
  public void makeExecutable(Path path, boolean confirm) {
1264

1265
    if (Files.exists(path)) {
5✔
1266
      if (skipPermissionsIfWindows(path)) {
4!
1267
        return;
×
1268
      }
1269
      PathPermissions existingPermissions = getFilePermissions(path);
4✔
1270
      PathPermissions executablePermissions = existingPermissions.makeExecutable();
3✔
1271
      boolean update = (executablePermissions != existingPermissions);
7✔
1272
      if (update) {
2✔
1273
        if (confirm) {
2!
1274
          boolean yesContinue = this.context.question(
×
1275
              "We want to execute {} but this command seems to lack executable permissions!\n"
1276
                  + "Most probably the tool vendor did forget to add x-flags in the binary release package.\n"
1277
                  + "Before running the command, we suggest to set executable permissions to the file:\n"
1278
                  + "{}\n"
1279
                  + "For security reasons we ask for your confirmation so please check this request.\n"
1280
                  + "Changing permissions from {} to {}.\n"
1281
                  + "Do you confirm to make the command executable before running it?", path.getFileName(), path, existingPermissions, executablePermissions);
×
1282
          if (!yesContinue) {
×
1283
            return;
×
1284
          }
1285
        }
1286
        setFilePermissions(path, executablePermissions, false);
6✔
1287
      } else {
1288
        LOG.trace("Executable flags already present so no need to set them for file {}", path);
4✔
1289
      }
1290
    } else {
1✔
1291
      LOG.warn("Cannot set executable flag on file that does not exist: {}", path);
4✔
1292
    }
1293
  }
1✔
1294

1295
  @Override
1296
  public PathPermissions getFilePermissions(Path path) {
1297

1298
    PathPermissions pathPermissions;
1299
    String info = "";
2✔
1300
    if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
1301
      info = "mocked-";
×
1302
      if (Files.isDirectory(path)) {
×
1303
        pathPermissions = PathPermissions.MODE_RWX_RX_RX;
×
1304
      } else {
1305
        Path parent = path.getParent();
×
1306
        if ((parent != null) && (parent.getFileName().toString().equals("bin"))) {
×
1307
          pathPermissions = PathPermissions.MODE_RWX_RX_RX;
×
1308
        } else {
1309
          pathPermissions = PathPermissions.MODE_RW_R_R;
×
1310
        }
1311
      }
×
1312
    } else {
1313
      Set<PosixFilePermission> permissions;
1314
      try {
1315
        // Read the current file permissions
1316
        permissions = Files.getPosixFilePermissions(path);
5✔
1317
      } catch (IOException e) {
×
1318
        throw new RuntimeException("Failed to get permissions for " + path, e);
×
1319
      }
1✔
1320
      pathPermissions = PathPermissions.of(permissions);
3✔
1321
    }
1322
    LOG.trace("Read {}permissions of {} as {}.", info, path, pathPermissions);
17✔
1323
    return pathPermissions;
2✔
1324
  }
1325

1326
  @Override
1327
  public void setFilePermissions(Path path, PathPermissions permissions, boolean logErrorAndContinue) {
1328

1329
    if (skipPermissionsIfWindows(path)) {
4!
1330
      return;
×
1331
    }
1332
    try {
1333
      LOG.debug("Setting permissions for {} to {}", path, permissions);
5✔
1334
      // Set the new permissions
1335
      Files.setPosixFilePermissions(path, permissions.toPosix());
5✔
1336
    } catch (IOException e) {
×
1337
      String message = "Failed to set permissions to " + permissions + " for path " + path;
×
1338
      if (logErrorAndContinue) {
×
1339
        LOG.warn(message, e);
×
1340
      } else {
1341
        throw new RuntimeException(message, e);
×
1342
      }
1343
    }
1✔
1344
  }
1✔
1345

1346
  private boolean skipPermissionsIfWindows(Path path) {
1347

1348
    if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
1349
      LOG.trace("Windows does not have file permissions hence omitting for {}", path);
×
1350
      return true;
×
1351
    }
1352
    return false;
2✔
1353
  }
1354

1355
  @Override
1356
  public void touch(Path file) {
1357

1358
    if (Files.exists(file)) {
5✔
1359
      try {
1360
        Files.setLastModifiedTime(file, FileTime.fromMillis(System.currentTimeMillis()));
5✔
1361
      } catch (IOException e) {
×
1362
        throw new IllegalStateException("Could not update modification-time of " + file, e);
×
1363
      }
1✔
1364
    } else {
1365
      try {
1366
        Files.createFile(file);
5✔
1367
      } catch (IOException e) {
1✔
1368
        throw new IllegalStateException("Could not create empty file " + file, e);
8✔
1369
      }
1✔
1370
    }
1371
  }
1✔
1372

1373
  @Override
1374
  public String readFileContent(Path file) {
1375

1376
    LOG.trace("Reading content of file from {}", file);
4✔
1377
    if (!Files.exists((file))) {
5!
1378
      LOG.debug("File {} does not exist", file);
×
1379
      return null;
×
1380
    }
1381
    try {
1382
      String content = Files.readString(file);
3✔
1383
      LOG.trace("Completed reading {} character(s) from file {}", content.length(), file);
7✔
1384
      return content;
2✔
1385
    } catch (IOException e) {
×
1386
      throw new IllegalStateException("Failed to read file " + file, e);
×
1387
    }
1388
  }
1389

1390
  @Override
1391
  public void writeFileContent(String content, Path file, boolean createParentDir) {
1392

1393
    if (createParentDir) {
2✔
1394
      mkdirs(file.getParent());
4✔
1395
    }
1396
    if (content == null) {
2!
1397
      content = "";
×
1398
    }
1399
    LOG.trace("Writing content with {} character(s) to file {}", content.length(), file);
7✔
1400
    if (Files.exists(file)) {
5✔
1401
      LOG.info("Overriding content of file {}", file);
4✔
1402
    }
1403
    try {
1404
      Files.writeString(file, content);
6✔
1405
      LOG.trace("Wrote content to file {}", file);
4✔
1406
    } catch (IOException e) {
×
1407
      throw new RuntimeException("Failed to write file " + file, e);
×
1408
    }
1✔
1409
  }
1✔
1410

1411
  @Override
1412
  public List<String> readFileLines(Path file) {
1413

1414
    LOG.trace("Reading lines of file from {}", file);
4✔
1415
    if (!Files.exists(file)) {
5✔
1416
      LOG.warn("File {} does not exist", file);
4✔
1417
      return null;
2✔
1418
    }
1419
    try {
1420
      List<String> content = Files.readAllLines(file);
3✔
1421
      LOG.trace("Completed reading {} lines from file {}", content.size(), file);
7✔
1422
      return content;
2✔
1423
    } catch (IOException e) {
×
1424
      throw new IllegalStateException("Failed to read file " + file, e);
×
1425
    }
1426
  }
1427

1428
  @Override
1429
  public void writeFileLines(List<String> content, Path file, boolean createParentDir) {
1430

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

1449
  @Override
1450
  public void readProperties(Path file, Properties properties) {
1451

1452
    try (Reader reader = Files.newBufferedReader(file)) {
3✔
1453
      properties.load(reader);
3✔
1454
      LOG.debug("Successfully loaded {} properties from {}", properties.size(), file);
7✔
1455
    } catch (IOException e) {
×
1456
      throw new IllegalStateException("Failed to read properties file: " + file, e);
×
1457
    }
1✔
1458
  }
1✔
1459

1460
  @Override
1461
  public void writeProperties(Properties properties, Path file, boolean createParentDir) {
1462

1463
    if (createParentDir) {
2✔
1464
      mkdirs(file.getParent());
4✔
1465
    }
1466
    try (Writer writer = Files.newBufferedWriter(file)) {
5✔
1467
      properties.store(writer, null); // do not get confused - Java still writes a date/time header that cannot be omitted
4✔
1468
      LOG.debug("Successfully saved {} properties to {}", properties.size(), file);
7✔
1469
    } catch (IOException e) {
×
1470
      throw new IllegalStateException("Failed to save properties file during tests.", e);
×
1471
    }
1✔
1472
  }
1✔
1473

1474
  @Override
1475
  public void readIniFile(Path file, IniFile iniFile) {
1476

1477
    if (!Files.exists(file)) {
5✔
1478
      LOG.debug("INI file {} does not exist.", iniFile);
4✔
1479
      return;
1✔
1480
    }
1481
    List<String> iniLines = readFileLines(file);
4✔
1482
    IniSection currentIniSection = iniFile.getInitialSection();
3✔
1483
    for (String line : iniLines) {
10✔
1484
      if (line.trim().startsWith("[")) {
5✔
1485
        currentIniSection = iniFile.getOrCreateSection(line);
5✔
1486
      } else if (line.isBlank() || IniComment.COMMENT_SYMBOLS.contains(line.trim().charAt(0))) {
11✔
1487
        currentIniSection.addComment(line);
4✔
1488
      } else {
1489
        int index = line.indexOf('=');
4✔
1490
        if (index > 0) {
2!
1491
          currentIniSection.setProperty(line);
3✔
1492
        }
1493
      }
1494
    }
1✔
1495
  }
1✔
1496

1497
  @Override
1498
  public void writeIniFile(IniFile iniFile, Path file, boolean createParentDir) {
1499

1500
    String iniString = iniFile.toString();
3✔
1501
    writeFileContent(iniString, file, createParentDir);
5✔
1502
  }
1✔
1503

1504
  @Override
1505
  public Duration getFileAge(Path path) {
1506

1507
    if (Files.exists(path)) {
5✔
1508
      try {
1509
        long currentTime = System.currentTimeMillis();
2✔
1510
        long fileModifiedTime = Files.getLastModifiedTime(path).toMillis();
6✔
1511
        return Duration.ofMillis(currentTime - fileModifiedTime);
5✔
1512
      } catch (IOException e) {
×
1513
        LOG.warn("Could not get modification-time of {}.", path, e);
×
1514
      }
×
1515
    } else {
1516
      LOG.debug("Path {} is missing - skipping modification-time and file age check.", path);
4✔
1517
    }
1518
    return null;
2✔
1519
  }
1520

1521
  @Override
1522
  public boolean isFileAgeRecent(Path path, Duration cacheDuration) {
1523

1524
    Duration age = getFileAge(path);
4✔
1525
    if (age == null) {
2✔
1526
      return false;
2✔
1527
    }
1528
    LOG.debug("The path {} was last updated {} ago and caching duration is {}.", path, age, cacheDuration);
17✔
1529
    return (age.toMillis() <= cacheDuration.toMillis());
10✔
1530
  }
1531
}
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