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

devonfw / IDEasy / 12708813826

10 Jan 2025 11:39AM UTC coverage: 67.541% (+0.06%) from 67.478%
12708813826

push

github

web-flow
#881: add self healing feature to add x-flags before running command (#904)

2577 of 4158 branches covered (61.98%)

Branch coverage included in aggregate %.

6670 of 9533 relevant lines covered (69.97%)

3.08 hits per line

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

64.12
cli/src/main/java/com/devonfw/tools/ide/io/FileAccessImpl.java
1
package com.devonfw.tools.ide.io;
2

3
import java.io.BufferedOutputStream;
4
import java.io.FileInputStream;
5
import java.io.FileOutputStream;
6
import java.io.IOException;
7
import java.io.InputStream;
8
import java.io.OutputStream;
9
import java.net.URI;
10
import java.net.http.HttpClient;
11
import java.net.http.HttpClient.Redirect;
12
import java.net.http.HttpRequest;
13
import java.net.http.HttpResponse;
14
import java.nio.file.FileSystem;
15
import java.nio.file.FileSystemException;
16
import java.nio.file.FileSystems;
17
import java.nio.file.Files;
18
import java.nio.file.LinkOption;
19
import java.nio.file.NoSuchFileException;
20
import java.nio.file.Path;
21
import java.nio.file.attribute.BasicFileAttributes;
22
import java.nio.file.attribute.FileTime;
23
import java.nio.file.attribute.PosixFilePermission;
24
import java.nio.file.attribute.PosixFilePermissions;
25
import java.security.DigestInputStream;
26
import java.security.MessageDigest;
27
import java.security.NoSuchAlgorithmException;
28
import java.time.LocalDateTime;
29
import java.util.ArrayList;
30
import java.util.HashSet;
31
import java.util.Iterator;
32
import java.util.List;
33
import java.util.Map;
34
import java.util.Set;
35
import java.util.function.Consumer;
36
import java.util.function.Function;
37
import java.util.function.Predicate;
38
import java.util.stream.Stream;
39

40
import org.apache.commons.compress.archivers.ArchiveEntry;
41
import org.apache.commons.compress.archivers.ArchiveInputStream;
42
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
43
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
44

45
import com.devonfw.tools.ide.cli.CliException;
46
import com.devonfw.tools.ide.cli.CliOfflineException;
47
import com.devonfw.tools.ide.context.IdeContext;
48
import com.devonfw.tools.ide.os.SystemInfoImpl;
49
import com.devonfw.tools.ide.process.ProcessContext;
50
import com.devonfw.tools.ide.url.model.file.UrlChecksum;
51
import com.devonfw.tools.ide.util.DateTimeUtil;
52
import com.devonfw.tools.ide.util.FilenameUtil;
53
import com.devonfw.tools.ide.util.HexUtil;
54

55
/**
56
 * Implementation of {@link FileAccess}.
57
 */
58
public class FileAccessImpl implements FileAccess {
59

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

62
  private static final String WINDOWS_FILE_LOCK_WARNING =
63
      "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"
64
          + WINDOWS_FILE_LOCK_DOCUMENTATION_PAGE;
65

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

68
  private final IdeContext context;
69

70
  /**
71
   * The constructor.
72
   *
73
   * @param context the {@link IdeContext} to use.
74
   */
75
  public FileAccessImpl(IdeContext context) {
76

77
    super();
2✔
78
    this.context = context;
3✔
79
  }
1✔
80

81
  private HttpClient createHttpClient(String url) {
82

83
    HttpClient.Builder builder = HttpClient.newBuilder().followRedirects(Redirect.ALWAYS);
4✔
84
    return builder.build();
3✔
85
  }
86

87
  @Override
88
  public void download(String url, Path target) {
89

90
    this.context.info("Trying to download {} from {}", target.getFileName(), url);
15✔
91
    mkdirs(target.getParent());
4✔
92
    try {
93
      if (this.context.isOffline()) {
4!
94
        throw CliOfflineException.ofDownloadViaUrl(url);
×
95
      }
96
      if (url.startsWith("http")) {
4✔
97

98
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)).GET().build();
7✔
99
        HttpClient client = createHttpClient(url);
4✔
100
        HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
5✔
101
        if (response.statusCode() == 200) {
4!
102
          downloadFileWithProgressBar(url, target, response);
5✔
103
        }
104
      } else if (url.startsWith("ftp") || url.startsWith("sftp")) {
9!
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

111
          copyFileWithProgressBar(source, target);
5✔
112
        } else {
113
          throw new IllegalArgumentException("Download path does not point to a downloadable file: " + url);
×
114
        }
115
      }
116
    } catch (Exception e) {
×
117
      throw new IllegalStateException("Failed to download file from URL " + url + " to " + target, e);
×
118
    }
1✔
119
  }
1✔
120

121
  /**
122
   * Downloads a file while showing a {@link IdeProgressBar}.
123
   *
124
   * @param url the url to download.
125
   * @param target Path of the target directory.
126
   * @param response the {@link HttpResponse} to use.
127
   */
128
  private void downloadFileWithProgressBar(String url, Path target, HttpResponse<InputStream> response) {
129

130
    long contentLength = response.headers().firstValueAsLong("content-length").orElse(-1);
7✔
131
    informAboutMissingContentLength(contentLength, url);
4✔
132

133
    byte[] data = new byte[1024];
3✔
134
    boolean fileComplete = false;
2✔
135
    int count;
136

137
    try (InputStream body = response.body();
4✔
138
        FileOutputStream fileOutput = new FileOutputStream(target.toFile());
6✔
139
        BufferedOutputStream bufferedOut = new BufferedOutputStream(fileOutput, data.length);
7✔
140
        IdeProgressBar pb = this.context.newProgressBarForDownload(contentLength)) {
5✔
141
      while (!fileComplete) {
2✔
142
        count = body.read(data);
4✔
143
        if (count <= 0) {
2✔
144
          fileComplete = true;
3✔
145
        } else {
146
          bufferedOut.write(data, 0, count);
5✔
147
          pb.stepBy(count);
5✔
148
        }
149
      }
150

151
    } catch (Exception e) {
×
152
      throw new RuntimeException(e);
×
153
    }
1✔
154
  }
1✔
155

156
  /**
157
   * Copies a file while displaying a progress bar.
158
   *
159
   * @param source Path of file to copy.
160
   * @param target Path of target directory.
161
   */
162
  private void copyFileWithProgressBar(Path source, Path target) throws IOException {
163

164
    try (InputStream in = new FileInputStream(source.toFile()); OutputStream out = new FileOutputStream(target.toFile())) {
12✔
165
      long size = getFileSize(source);
4✔
166
      byte[] buf = new byte[1024];
3✔
167
      try (IdeProgressBar pb = this.context.newProgressbarForCopying(size)) {
5✔
168
        int readBytes;
169
        while ((readBytes = in.read(buf)) > 0) {
6✔
170
          out.write(buf, 0, readBytes);
5✔
171
          if (size > 0) {
4!
172
            pb.stepBy(readBytes);
5✔
173
          }
174
        }
175
      } catch (Exception e) {
×
176
        throw new RuntimeException(e);
×
177
      }
1✔
178
    }
179
  }
1✔
180

181
  private void informAboutMissingContentLength(long contentLength, String url) {
182

183
    if (contentLength < 0) {
4✔
184
      this.context.warning("Content-Length was not provided by download from {}", url);
10✔
185
    }
186
  }
1✔
187

188
  @Override
189
  public void mkdirs(Path directory) {
190

191
    if (Files.isDirectory(directory)) {
5✔
192
      return;
1✔
193
    }
194
    this.context.trace("Creating directory {}", directory);
10✔
195
    try {
196
      Files.createDirectories(directory);
5✔
197
    } catch (IOException e) {
×
198
      throw new IllegalStateException("Failed to create directory " + directory, e);
×
199
    }
1✔
200
  }
1✔
201

202
  @Override
203
  public boolean isFile(Path file) {
204

205
    if (!Files.exists(file)) {
5!
206
      this.context.trace("File {} does not exist", file);
×
207
      return false;
×
208
    }
209
    if (Files.isDirectory(file)) {
5!
210
      this.context.trace("Path {} is a directory but a regular file was expected", file);
×
211
      return false;
×
212
    }
213
    return true;
2✔
214
  }
215

216
  @Override
217
  public boolean isExpectedFolder(Path folder) {
218

219
    if (Files.isDirectory(folder)) {
5✔
220
      return true;
2✔
221
    }
222
    this.context.warning("Expected folder was not found at {}", folder);
10✔
223
    return false;
2✔
224
  }
225

226
  @Override
227
  public String checksum(Path file) {
228

229
    try {
230
      MessageDigest md = MessageDigest.getInstance(UrlChecksum.HASH_ALGORITHM);
×
231
      byte[] buffer = new byte[1024];
×
232
      try (InputStream is = Files.newInputStream(file); DigestInputStream dis = new DigestInputStream(is, md)) {
×
233
        int read = 0;
×
234
        while (read >= 0) {
×
235
          read = dis.read(buffer);
×
236
        }
237
      } catch (Exception e) {
×
238
        throw new IllegalStateException("Failed to read and hash file " + file, e);
×
239
      }
×
240
      byte[] digestBytes = md.digest();
×
241
      return HexUtil.toHexString(digestBytes);
×
242
    } catch (NoSuchAlgorithmException e) {
×
243
      throw new IllegalStateException("No such hash algorithm " + UrlChecksum.HASH_ALGORITHM, e);
×
244
    }
245
  }
246

247
  private boolean isJunction(Path path) {
248

249
    if (!SystemInfoImpl.INSTANCE.isWindows()) {
3!
250
      return false;
2✔
251
    }
252

253
    try {
254
      BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
×
255
      return attr.isOther() && attr.isDirectory();
×
256
    } catch (NoSuchFileException e) {
×
257
      return false; // file doesn't exist
×
258
    } catch (IOException e) {
×
259
      // errors in reading the attributes of the file
260
      throw new IllegalStateException("An unexpected error occurred whilst checking if the file: " + path + " is a junction", e);
×
261
    }
262
  }
263

264
  @Override
265
  public void backup(Path fileOrFolder) {
266

267
    if (Files.isSymbolicLink(fileOrFolder) || isJunction(fileOrFolder)) {
7!
268
      delete(fileOrFolder);
×
269
    } else {
270
      // fileOrFolder is a directory
271
      Path backupPath = this.context.getIdeHome().resolve(IdeContext.FOLDER_UPDATES).resolve(IdeContext.FOLDER_BACKUPS);
8✔
272
      LocalDateTime now = LocalDateTime.now();
2✔
273
      String date = DateTimeUtil.formatDate(now);
3✔
274
      String time = DateTimeUtil.formatTime(now);
3✔
275
      Path backupDatePath = backupPath.resolve(date);
4✔
276
      mkdirs(backupDatePath);
3✔
277
      Path target = backupDatePath.resolve(fileOrFolder.getFileName().toString() + "_" + time);
8✔
278
      this.context.info("Creating backup by moving {} to {}", fileOrFolder, target);
14✔
279
      move(fileOrFolder, target);
4✔
280
    }
281
  }
1✔
282

283
  @Override
284
  public void move(Path source, Path targetDir) {
285

286
    this.context.trace("Moving {} to {}", source, targetDir);
14✔
287
    try {
288
      Files.move(source, targetDir);
6✔
289
    } catch (IOException e) {
×
290
      String fileType = Files.isSymbolicLink(source) ? "symlink" : isJunction(source) ? "junction" : Files.isDirectory(source) ? "directory" : "file";
×
291
      String message = "Failed to move " + fileType + ": " + source + " to " + targetDir + ".";
×
292
      if (this.context.getSystemInfo().isWindows()) {
×
293
        message = message + "\n" + WINDOWS_FILE_LOCK_WARNING;
×
294
      }
295
      throw new IllegalStateException(message, e);
×
296
    }
1✔
297
  }
1✔
298

299
  @Override
300
  public void copy(Path source, Path target, FileCopyMode mode, PathCopyListener listener) {
301

302
    if (mode != FileCopyMode.COPY_TREE_CONTENT) {
3✔
303
      // if we want to copy the file or folder "source" to the existing folder "target" in a shell this will copy
304
      // source into that folder so that we as a result have a copy in "target/source".
305
      // With Java NIO the raw copy method will fail as we cannot copy "source" to the path of the "target" folder.
306
      // For folders we want the same behavior as the linux "cp -r" command so that the "source" folder is copied
307
      // and not only its content what also makes it consistent with the move method that also behaves this way.
308
      // Therefore we need to add the filename (foldername) of "source" to the "target" path before.
309
      // For the rare cases, where we want to copy the content of a folder (cp -r source/* target) we support
310
      // it via the COPY_TREE_CONTENT mode.
311
      Path fileName = source.getFileName();
3✔
312
      if (fileName != null) { // if filename is null, we are copying the root of a (virtual filesystem)
2✔
313
        target = target.resolve(fileName.toString());
5✔
314
      }
315
    }
316
    boolean fileOnly = mode.isFileOnly();
3✔
317
    String operation = mode.getOperation();
3✔
318
    if (mode.isExtract()) {
3✔
319
      this.context.debug("Starting to {} to {}", operation, target);
15✔
320
    } else {
321
      if (fileOnly) {
2✔
322
        this.context.debug("Starting to {} file {} to {}", operation, source, target);
19✔
323
      } else {
324
        this.context.debug("Starting to {} {} recursively to {}", operation, source, target);
18✔
325
      }
326
    }
327
    if (fileOnly && Files.isDirectory(source)) {
7!
328
      throw new IllegalStateException("Expected file but found a directory to copy at " + source);
×
329
    }
330
    if (mode.isFailIfExists()) {
3✔
331
      if (Files.exists(target)) {
5!
332
        throw new IllegalStateException("Failed to " + operation + " " + source + " to already existing target " + target);
×
333
      }
334
    } else if (mode == FileCopyMode.COPY_TREE_OVERRIDE_TREE) {
3✔
335
      delete(target);
3✔
336
    }
337
    try {
338
      copyRecursive(source, target, mode, listener);
6✔
339
    } catch (IOException e) {
×
340
      throw new IllegalStateException("Failed to " + operation + " " + source + " to " + target, e);
×
341
    }
1✔
342
  }
1✔
343

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

346
    if (Files.isDirectory(source)) {
5✔
347
      mkdirs(target);
3✔
348
      try (Stream<Path> childStream = Files.list(source)) {
3✔
349
        Iterator<Path> iterator = childStream.iterator();
3✔
350
        while (iterator.hasNext()) {
3✔
351
          Path child = iterator.next();
4✔
352
          copyRecursive(child, target.resolve(child.getFileName().toString()), mode, listener);
10✔
353
        }
1✔
354
      }
355
      listener.onCopy(source, target, true);
6✔
356
    } else if (Files.exists(source)) {
5!
357
      if (mode.isOverrideFile()) {
3✔
358
        delete(target);
3✔
359
      }
360
      this.context.trace("Starting to {} {} to {}", mode.getOperation(), source, target);
19✔
361
      Files.copy(source, target);
6✔
362
      listener.onCopy(source, target, false);
6✔
363
    } else {
364
      throw new IOException("Path " + source + " does not exist.");
×
365
    }
366
  }
1✔
367

368
  /**
369
   * 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
370
   * {@link Path} that is neither a symbolic link nor a Windows junction.
371
   *
372
   * @param path the {@link Path} to delete.
373
   * @throws IOException if the actual {@link Files#delete(Path) deletion} fails.
374
   */
375
  private void deleteLinkIfExists(Path path) throws IOException {
376

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

380
    assert !(isSymlink && isJunction);
5!
381

382
    if (isJunction || isSymlink) {
4!
383
      this.context.info("Deleting previous " + (isJunction ? "junction" : "symlink") + " at " + path);
8!
384
      Files.delete(path);
2✔
385
    }
386
  }
1✔
387

388
  /**
389
   * Adapts the given {@link Path} to be relative or absolute depending on the given {@code relative} flag. Additionally, {@link Path#toRealPath(LinkOption...)}
390
   * is applied to {@code source}.
391
   *
392
   * @param source the {@link Path} to adapt.
393
   * @param targetLink the {@link Path} used to calculate the relative path to the {@code source} if {@code relative} is set to {@code true}.
394
   * @param relative the {@code relative} flag.
395
   * @return the adapted {@link Path}.
396
   * @see FileAccessImpl#symlink(Path, Path, boolean)
397
   */
398
  private Path adaptPath(Path source, Path targetLink, boolean relative) throws IOException {
399

400
    if (source.isAbsolute()) {
3✔
401
      try {
402
        source = source.toRealPath(LinkOption.NOFOLLOW_LINKS); // to transform ../d1/../d2 to ../d2
9✔
403
      } catch (IOException e) {
×
404
        throw new IOException("Calling toRealPath() on the source (" + source + ") in method FileAccessImpl.adaptPath() failed.", e);
×
405
      }
1✔
406
      if (relative) {
2✔
407
        source = targetLink.getParent().relativize(source);
5✔
408
        // to make relative links like this work: dir/link -> dir
409
        source = (source.toString().isEmpty()) ? Path.of(".") : source;
12✔
410
      }
411
    } else { // source is relative
412
      if (relative) {
2✔
413
        // even though the source is already relative, toRealPath should be called to transform paths like
414
        // this ../d1/../d2 to ../d2
415
        source = targetLink.getParent().relativize(targetLink.resolveSibling(source).toRealPath(LinkOption.NOFOLLOW_LINKS));
14✔
416
        source = (source.toString().isEmpty()) ? Path.of(".") : source;
12✔
417
      } else { // !relative
418
        try {
419
          source = targetLink.resolveSibling(source).toRealPath(LinkOption.NOFOLLOW_LINKS);
11✔
420
        } catch (IOException e) {
×
421
          throw new IOException("Calling toRealPath() on " + targetLink + ".resolveSibling(" + source + ") in method FileAccessImpl.adaptPath() failed.", e);
×
422
        }
1✔
423
      }
424
    }
425
    return source;
2✔
426
  }
427

428
  /**
429
   * Creates a Windows junction at {@code targetLink} pointing to {@code source}.
430
   *
431
   * @param source must be another Windows junction or a directory.
432
   * @param targetLink the location of the Windows junction.
433
   */
434
  private void createWindowsJunction(Path source, Path targetLink) {
435

436
    this.context.trace("Creating a Windows junction at " + targetLink + " with " + source + " as source.");
×
437
    Path fallbackPath;
438
    if (!source.isAbsolute()) {
×
439
      this.context.warning("You are on Windows and you do not have permissions to create symbolic links. Junctions are used as an "
×
440
          + "alternative, however, these can not point to relative paths. So the source (" + source + ") is interpreted as an absolute path.");
441
      try {
442
        fallbackPath = targetLink.resolveSibling(source).toRealPath(LinkOption.NOFOLLOW_LINKS);
×
443
      } catch (IOException e) {
×
444
        throw new IllegalStateException(
×
445
            "Since Windows junctions are used, the source must be an absolute path. The transformation of the passed " + "source (" + source
446
                + ") to an absolute path failed.", e);
447
      }
×
448

449
    } else {
450
      fallbackPath = source;
×
451
    }
452
    if (!Files.isDirectory(fallbackPath)) { // if source is a junction. This returns true as well.
×
453
      throw new IllegalStateException(
×
454
          "These junctions can only point to directories or other junctions. Please make sure that the source (" + fallbackPath + ") is one of these.");
455
    }
456
    this.context.newProcess().executable("cmd").addArgs("/c", "mklink", "/d", "/j", targetLink.toString(), fallbackPath.toString()).run();
×
457
  }
×
458

459
  @Override
460
  public void symlink(Path source, Path targetLink, boolean relative) {
461

462
    Path adaptedSource = null;
2✔
463
    try {
464
      adaptedSource = adaptPath(source, targetLink, relative);
6✔
465
    } catch (IOException e) {
×
466
      throw new IllegalStateException("Failed to adapt source for source (" + source + ") target (" + targetLink + ") and relative (" + relative + ")", e);
×
467
    }
1✔
468
    this.context.trace("Creating {} symbolic link {} pointing to {}", adaptedSource.isAbsolute() ? "" : "relative", targetLink, adaptedSource);
23✔
469

470
    try {
471
      deleteLinkIfExists(targetLink);
3✔
472
    } catch (IOException e) {
×
473
      throw new IllegalStateException("Failed to delete previous symlink or Windows junction at " + targetLink, e);
×
474
    }
1✔
475

476
    try {
477
      Files.createSymbolicLink(targetLink, adaptedSource);
6✔
478
    } catch (FileSystemException e) {
×
479
      if (SystemInfoImpl.INSTANCE.isWindows()) {
×
480
        this.context.info("Due to lack of permissions, Microsoft's mklink with junction had to be used to create "
×
481
            + "a Symlink. See https://github.com/devonfw/IDEasy/blob/main/documentation/symlinks.asciidoc for " + "further details. Error was: "
482
            + e.getMessage());
×
483
        createWindowsJunction(adaptedSource, targetLink);
×
484
      } else {
485
        throw new RuntimeException(e);
×
486
      }
487
    } catch (IOException e) {
×
488
      throw new IllegalStateException(
×
489
          "Failed to create a " + (adaptedSource.isAbsolute() ? "" : "relative") + "symbolic link " + targetLink + " pointing to " + source, e);
×
490
    }
1✔
491
  }
1✔
492

493
  @Override
494
  public Path toRealPath(Path path) {
495

496
    try {
497
      Path realPath = path.toRealPath();
×
498
      if (!realPath.equals(path)) {
×
499
        this.context.trace("Resolved path {} to {}", path, realPath);
×
500
      }
501
      return realPath;
×
502
    } catch (IOException e) {
×
503
      throw new IllegalStateException("Failed to get real path for " + path, e);
×
504
    }
505
  }
506

507
  @Override
508
  public Path createTempDir(String name) {
509

510
    try {
511
      Path tmp = this.context.getTempPath();
4✔
512
      Path tempDir = tmp.resolve(name);
4✔
513
      int tries = 1;
2✔
514
      while (Files.exists(tempDir)) {
5!
515
        long id = System.nanoTime() & 0xFFFF;
×
516
        tempDir = tmp.resolve(name + "-" + id);
×
517
        tries++;
×
518
        if (tries > 200) {
×
519
          throw new IOException("Unable to create unique name!");
×
520
        }
521
      }
×
522
      return Files.createDirectory(tempDir);
5✔
523
    } catch (IOException e) {
×
524
      throw new IllegalStateException("Failed to create temporary directory with prefix '" + name + "'!", e);
×
525
    }
526
  }
527

528
  @Override
529
  public void extract(Path archiveFile, Path targetDir, Consumer<Path> postExtractHook, boolean extract) {
530

531
    if (Files.isDirectory(archiveFile)) {
5✔
532
      // TODO: check this case
533
      Path properInstallDir = archiveFile; // getProperInstallationSubDirOf(archiveFile, archiveFile);
2✔
534
      this.context.warning("Found directory for download at {} hence copying without extraction!", archiveFile);
10✔
535
      copy(properInstallDir, targetDir, FileCopyMode.COPY_TREE_CONTENT);
5✔
536
      postExtractHook(postExtractHook, targetDir);
4✔
537
      return;
1✔
538
    } else if (!extract) {
2!
539
      mkdirs(targetDir);
×
540
      move(archiveFile, targetDir.resolve(archiveFile.getFileName()));
×
541
      return;
×
542
    }
543
    Path tmpDir = createTempDir("extract-" + archiveFile.getFileName());
6✔
544
    this.context.trace("Trying to extract the downloaded file {} to {} and move it to {}.", archiveFile, tmpDir, targetDir);
18✔
545
    String filename = archiveFile.getFileName().toString();
4✔
546
    TarCompression tarCompression = TarCompression.of(filename);
3✔
547
    if (tarCompression != null) {
2✔
548
      extractTar(archiveFile, tmpDir, tarCompression);
6✔
549
    } else {
550
      String extension = FilenameUtil.getExtension(filename);
3✔
551
      if (extension == null) {
2!
552
        throw new IllegalStateException("Unknown archive format without extension - can not extract " + archiveFile);
×
553
      } else {
554
        this.context.trace("Determined file extension {}", extension);
10✔
555
      }
556
      switch (extension) {
8!
557
        case "zip" -> extractZip(archiveFile, tmpDir);
×
558
        case "jar" -> extractJar(archiveFile, tmpDir);
5✔
559
        case "dmg" -> extractDmg(archiveFile, tmpDir);
×
560
        case "msi" -> extractMsi(archiveFile, tmpDir);
×
561
        case "pkg" -> extractPkg(archiveFile, tmpDir);
×
562
        default -> throw new IllegalStateException("Unknown archive format " + extension + ". Can not extract " + archiveFile);
×
563
      }
564
    }
565
    Path properInstallDir = getProperInstallationSubDirOf(tmpDir, archiveFile);
5✔
566
    postExtractHook(postExtractHook, properInstallDir);
4✔
567
    move(properInstallDir, targetDir);
4✔
568
    delete(tmpDir);
3✔
569
  }
1✔
570

571
  private void postExtractHook(Consumer<Path> postExtractHook, Path properInstallDir) {
572

573
    if (postExtractHook != null) {
2✔
574
      postExtractHook.accept(properInstallDir);
3✔
575
    }
576
  }
1✔
577

578
  /**
579
   * @param path the {@link Path} to start the recursive search from.
580
   * @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
581
   *     item in their respective directory and {@code s} is not named "bin".
582
   */
583
  private Path getProperInstallationSubDirOf(Path path, Path archiveFile) {
584

585
    try (Stream<Path> stream = Files.list(path)) {
3✔
586
      Path[] subFiles = stream.toArray(Path[]::new);
8✔
587
      if (subFiles.length == 0) {
3!
588
        throw new CliException("The downloaded package " + archiveFile + " seems to be empty as you can check in the extracted folder " + path);
×
589
      } else if (subFiles.length == 1) {
4✔
590
        String filename = subFiles[0].getFileName().toString();
6✔
591
        if (!filename.equals(IdeContext.FOLDER_BIN) && !filename.equals(IdeContext.FOLDER_CONTENTS) && !filename.endsWith(".app") && Files.isDirectory(
19!
592
            subFiles[0])) {
593
          return getProperInstallationSubDirOf(subFiles[0], archiveFile);
9✔
594
        }
595
      }
596
      return path;
4✔
597
    } catch (IOException e) {
4!
598
      throw new IllegalStateException("Failed to get sub-files of " + path);
×
599
    }
600
  }
601

602
  @Override
603
  public void extractZip(Path file, Path targetDir) {
604

605
    this.context.info("Extracting ZIP file {} to {}", file, targetDir);
14✔
606
    URI uri = URI.create("jar:" + file.toUri());
5✔
607
    try (FileSystem fs = FileSystems.newFileSystem(uri, FS_ENV)) {
4✔
608
      long size = 0;
2✔
609
      for (Path root : fs.getRootDirectories()) {
11✔
610
        size += getFileSizeRecursive(root);
6✔
611
      }
1✔
612
      try (final IdeProgressBar progressBar = this.context.newProgressbarForExtracting(size)) {
5✔
613
        for (Path root : fs.getRootDirectories()) {
11✔
614
          copy(root, targetDir, FileCopyMode.EXTRACT, (s, t, d) -> onFileCopiedFromZip(s, t, d, progressBar));
15✔
615
        }
1✔
616
      }
617
    } catch (IOException e) {
×
618
      throw new IllegalStateException("Failed to extract " + file + " to " + targetDir, e);
×
619
    }
1✔
620
  }
1✔
621

622
  @SuppressWarnings("unchecked")
623
  private void onFileCopiedFromZip(Path source, Path target, boolean directory, IdeProgressBar progressBar) {
624

625
    if (directory) {
2✔
626
      return;
1✔
627
    }
628
    if (!context.getSystemInfo().isWindows()) {
5✔
629
      try {
630
        Object attribute = Files.getAttribute(source, "zip:permissions");
6✔
631
        if (attribute instanceof Set<?> permissionSet) {
6✔
632
          Files.setPosixFilePermissions(target, (Set<PosixFilePermission>) permissionSet);
4✔
633
        }
634
      } catch (Exception e) {
×
635
        context.error(e, "Failed to transfer zip permissions for {}", target);
×
636
      }
1✔
637
    }
638
    progressBar.stepBy(getFileSize(target));
5✔
639
  }
1✔
640

641
  @Override
642
  public void extractTar(Path file, Path targetDir, TarCompression compression) {
643

644
    extractArchive(file, targetDir, in -> new TarArchiveInputStream(compression.unpack(in)));
13✔
645
  }
1✔
646

647
  @Override
648
  public void extractJar(Path file, Path targetDir) {
649

650
    extractZip(file, targetDir);
4✔
651
  }
1✔
652

653
  /**
654
   * @param permissions The integer as returned by {@link TarArchiveEntry#getMode()} that represents the file permissions of a file on a Unix file system.
655
   * @return A String representing the file permissions. E.g. "rwxrwxr-x" or "rw-rw-r--"
656
   */
657
  public static String generatePermissionString(int permissions) {
658

659
    // Ensure that only the last 9 bits are considered
660
    permissions &= 0b111111111;
4✔
661

662
    StringBuilder permissionStringBuilder = new StringBuilder("rwxrwxrwx");
5✔
663
    for (int i = 0; i < 9; i++) {
7✔
664
      int mask = 1 << i;
4✔
665
      char currentChar = ((permissions & mask) != 0) ? permissionStringBuilder.charAt(8 - i) : '-';
12✔
666
      permissionStringBuilder.setCharAt(8 - i, currentChar);
6✔
667
    }
668

669
    return permissionStringBuilder.toString();
3✔
670
  }
671

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

674
    this.context.info("Extracting TAR file {} to {}", file, targetDir);
14✔
675
    try (InputStream is = Files.newInputStream(file);
5✔
676
        ArchiveInputStream<?> ais = unpacker.apply(is);
5✔
677
        IdeProgressBar pb = this.context.newProgressbarForExtracting(getFileSize(file))) {
7✔
678

679
      ArchiveEntry entry = ais.getNextEntry();
3✔
680
      boolean isTar = ais instanceof TarArchiveInputStream;
3✔
681
      while (entry != null) {
2✔
682
        String permissionStr = null;
2✔
683
        if (isTar) {
2!
684
          int tarMode = ((TarArchiveEntry) entry).getMode();
4✔
685
          permissionStr = generatePermissionString(tarMode);
3✔
686
        }
687
        Path entryName = Path.of(entry.getName());
6✔
688
        Path entryPath = targetDir.resolve(entryName).toAbsolutePath();
5✔
689
        if (!entryPath.startsWith(targetDir)) {
4!
690
          throw new IOException("Preventing path traversal attack from " + entryName + " to " + entryPath);
×
691
        }
692
        if (entry.isDirectory()) {
3✔
693
          mkdirs(entryPath);
4✔
694
        } else {
695
          // ensure the file can also be created if directory entry was missing or out of order...
696
          mkdirs(entryPath.getParent());
4✔
697
          Files.copy(ais, entryPath);
6✔
698
        }
699
        if (isTar && !this.context.getSystemInfo().isWindows()) {
7!
700
          Set<PosixFilePermission> permissions = PosixFilePermissions.fromString(permissionStr);
3✔
701
          Files.setPosixFilePermissions(entryPath, permissions);
4✔
702
        }
703
        pb.stepBy(entry.getSize());
4✔
704
        entry = ais.getNextEntry();
3✔
705
      }
1✔
706
    } catch (IOException e) {
×
707
      throw new IllegalStateException("Failed to extract " + file + " to " + targetDir, e);
×
708
    }
1✔
709
  }
1✔
710

711
  @Override
712
  public void extractDmg(Path file, Path targetDir) {
713

714
    this.context.info("Extracting DMG file {} to {}", file, targetDir);
×
715
    assert this.context.getSystemInfo().isMac();
×
716

717
    Path mountPath = this.context.getIdeHome().resolve(IdeContext.FOLDER_UPDATES).resolve(IdeContext.FOLDER_VOLUME);
×
718
    mkdirs(mountPath);
×
719
    ProcessContext pc = this.context.newProcess();
×
720
    pc.executable("hdiutil");
×
721
    pc.addArgs("attach", "-quiet", "-nobrowse", "-mountpoint", mountPath, file);
×
722
    pc.run();
×
723
    Path appPath = findFirst(mountPath, p -> p.getFileName().toString().endsWith(".app"), false);
×
724
    if (appPath == null) {
×
725
      throw new IllegalStateException("Failed to unpack DMG as no MacOS *.app was found in file " + file);
×
726
    }
727

728
    copy(appPath, targetDir, FileCopyMode.COPY_TREE_OVERRIDE_TREE);
×
729
    pc.addArgs("detach", "-force", mountPath);
×
730
    pc.run();
×
731
  }
×
732

733
  @Override
734
  public void extractMsi(Path file, Path targetDir) {
735

736
    this.context.info("Extracting MSI file {} to {}", file, targetDir);
×
737
    this.context.newProcess().executable("msiexec").addArgs("/a", file, "/qn", "TARGETDIR=" + targetDir).run();
×
738
    // msiexec also creates a copy of the MSI
739
    Path msiCopy = targetDir.resolve(file.getFileName());
×
740
    delete(msiCopy);
×
741
  }
×
742

743
  @Override
744
  public void extractPkg(Path file, Path targetDir) {
745

746
    this.context.info("Extracting PKG file {} to {}", file, targetDir);
×
747
    Path tmpDirPkg = createTempDir("ide-pkg-");
×
748
    ProcessContext pc = this.context.newProcess();
×
749
    // we might also be able to use cpio from commons-compression instead of external xar...
750
    pc.executable("xar").addArgs("-C", tmpDirPkg, "-xf", file).run();
×
751
    Path contentPath = findFirst(tmpDirPkg, p -> p.getFileName().toString().equals("Payload"), true);
×
752
    extractTar(contentPath, targetDir, TarCompression.GZ);
×
753
    delete(tmpDirPkg);
×
754
  }
×
755

756
  @Override
757
  public void delete(Path path) {
758

759
    if (!Files.exists(path)) {
5✔
760
      this.context.trace("Deleting {} skipped as the path does not exist.", path);
10✔
761
      return;
1✔
762
    }
763
    this.context.debug("Deleting {} ...", path);
10✔
764
    try {
765
      if (Files.isSymbolicLink(path) || isJunction(path)) {
7!
766
        Files.delete(path);
×
767
      } else {
768
        deleteRecursive(path);
3✔
769
      }
770
    } catch (IOException e) {
×
771
      throw new IllegalStateException("Failed to delete " + path, e);
×
772
    }
1✔
773
  }
1✔
774

775
  private void deleteRecursive(Path path) throws IOException {
776

777
    if (Files.isDirectory(path)) {
5✔
778
      try (Stream<Path> childStream = Files.list(path)) {
3✔
779
        Iterator<Path> iterator = childStream.iterator();
3✔
780
        while (iterator.hasNext()) {
3✔
781
          Path child = iterator.next();
4✔
782
          deleteRecursive(child);
3✔
783
        }
1✔
784
      }
785
    }
786
    this.context.trace("Deleting {} ...", path);
10✔
787
    Files.delete(path);
2✔
788
  }
1✔
789

790
  @Override
791
  public Path findFirst(Path dir, Predicate<Path> filter, boolean recursive) {
792

793
    try {
794
      if (!Files.isDirectory(dir)) {
5✔
795
        return null;
2✔
796
      }
797
      return findFirstRecursive(dir, filter, recursive);
6✔
798
    } catch (IOException e) {
×
799
      throw new IllegalStateException("Failed to search for file in " + dir, e);
×
800
    }
801
  }
802

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

805
    List<Path> folders = null;
2✔
806
    try (Stream<Path> childStream = Files.list(dir)) {
3✔
807
      Iterator<Path> iterator = childStream.iterator();
3✔
808
      while (iterator.hasNext()) {
3✔
809
        Path child = iterator.next();
4✔
810
        if (filter.test(child)) {
4✔
811
          return child;
4✔
812
        } else if (recursive && Files.isDirectory(child)) {
2!
813
          if (folders == null) {
×
814
            folders = new ArrayList<>();
×
815
          }
816
          folders.add(child);
×
817
        }
818
      }
1✔
819
    }
4!
820
    if (folders != null) {
2!
821
      for (Path child : folders) {
×
822
        Path match = findFirstRecursive(child, filter, recursive);
×
823
        if (match != null) {
×
824
          return match;
×
825
        }
826
      }
×
827
    }
828
    return null;
2✔
829
  }
830

831
  @Override
832
  public List<Path> listChildren(Path dir, Predicate<Path> filter) {
833

834
    if (!Files.isDirectory(dir)) {
5✔
835
      return List.of();
2✔
836
    }
837
    List<Path> children = new ArrayList<>();
4✔
838
    try (Stream<Path> childStream = Files.list(dir)) {
3✔
839
      Iterator<Path> iterator = childStream.iterator();
3✔
840
      while (iterator.hasNext()) {
3✔
841
        Path child = iterator.next();
4✔
842
        if (filter.test(child)) {
4!
843
          this.context.trace("Accepted file {}", child);
10✔
844
          children.add(child);
5✔
845
        } else {
846
          this.context.trace("Ignoring file {} according to filter", child);
×
847
        }
848
      }
1✔
849
    } catch (IOException e) {
×
850
      throw new IllegalStateException("Failed to find children of directory " + dir, e);
×
851
    }
1✔
852
    return children;
2✔
853
  }
854

855
  @Override
856
  public boolean isEmptyDir(Path dir) {
857

858
    return listChildren(dir, f -> true).isEmpty();
8✔
859
  }
860

861
  private long getFileSize(Path file) {
862

863
    try {
864
      return Files.size(file);
3✔
865
    } catch (IOException e) {
×
866
      this.context.warning(e.getMessage(), e);
×
867
      return 0;
×
868
    }
869
  }
870

871
  private long getFileSizeRecursive(Path path) {
872

873
    long size = 0;
2✔
874
    if (Files.isDirectory(path)) {
5✔
875
      try (Stream<Path> childStream = Files.list(path)) {
3✔
876
        Iterator<Path> iterator = childStream.iterator();
3✔
877
        while (iterator.hasNext()) {
3✔
878
          Path child = iterator.next();
4✔
879
          size += getFileSizeRecursive(child);
6✔
880
        }
1✔
881
      } catch (IOException e) {
×
882
        throw new RuntimeException("Failed to iterate children of folder " + path, e);
×
883
      }
1✔
884
    } else {
885
      size += getFileSize(path);
6✔
886
    }
887
    return size;
2✔
888
  }
889

890
  @Override
891
  public Path findExistingFile(String fileName, List<Path> searchDirs) {
892

893
    for (Path dir : searchDirs) {
10!
894
      Path filePath = dir.resolve(fileName);
4✔
895
      try {
896
        if (Files.exists(filePath)) {
5!
897
          return filePath;
2✔
898
        }
899
      } catch (Exception e) {
×
900
        throw new IllegalStateException("Unexpected error while checking existence of file " + filePath + " .", e);
×
901
      }
×
902
    }
×
903
    return null;
×
904
  }
905

906
  @Override
907
  public void makeExecutable(Path file, boolean confirm) {
908

909
    if (Files.exists(file)) {
5✔
910
      if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
911
        this.context.trace("Windows does not have executable flags hence omitting for file {}", file);
×
912
        return;
×
913
      }
914
      try {
915
        // Read the current file permissions
916
        Set<PosixFilePermission> existingPermissions = Files.getPosixFilePermissions(file);
5✔
917

918
        // Add execute permission for all users
919
        Set<PosixFilePermission> executablePermissions = new HashSet<>(existingPermissions);
5✔
920
        boolean update = false;
2✔
921
        update |= executablePermissions.add(PosixFilePermission.OWNER_EXECUTE);
6✔
922
        update |= executablePermissions.add(PosixFilePermission.GROUP_EXECUTE);
6✔
923
        update |= executablePermissions.add(PosixFilePermission.OTHERS_EXECUTE);
6✔
924

925
        if (update) {
2!
926
          if (confirm) {
×
927
            boolean yesContinue = this.context.question(
×
928
                "We want to execute " + file.getFileName() + " but this command seems to lack executable permissions!\n"
×
929
                    + "Most probably the tool vendor did forgot to add x-flags in the binary release package.\n"
930
                    + "Before running the command, we suggest to set executable permissions to the file:\n"
931
                    + file + "\n"
932
                    + "For security reasons we ask for your confirmation so please check this request.\n"
933
                    + "Changing permissions from " + PosixFilePermissions.toString(existingPermissions) + " to " + PosixFilePermissions.toString(
×
934
                    executablePermissions) + ".\n"
935
                    + "Do you confirm to make the command executable before running it?");
936
            if (!yesContinue) {
×
937
              return;
×
938
            }
939
          }
940
          this.context.debug("Setting executable flags for file {}", file);
×
941
          // Set the new permissions
942
          Files.setPosixFilePermissions(file, executablePermissions);
×
943
        } else {
944
          this.context.trace("Executable flags already present so no need to set them for file {}", file);
10✔
945
        }
946
      } catch (IOException e) {
×
947
        throw new RuntimeException(e);
×
948
      }
1✔
949
    } else {
950
      this.context.warning("Cannot set executable flag on file that does not exist: {}", file);
10✔
951
    }
952
  }
1✔
953

954
  @Override
955
  public void touch(Path file) {
956

957
    if (Files.exists(file)) {
5✔
958
      try {
959
        Files.setLastModifiedTime(file, FileTime.fromMillis(System.currentTimeMillis()));
5✔
960
      } catch (IOException e) {
×
961
        throw new IllegalStateException("Could not update modification-time of " + file, e);
×
962
      }
1✔
963
    } else {
964
      try {
965
        Files.createFile(file);
5✔
966
      } catch (IOException e) {
1✔
967
        throw new IllegalStateException("Could not create empty file " + file, e);
7✔
968
      }
1✔
969
    }
970
  }
1✔
971
}
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