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

devonfw / IDEasy / 12746499935

13 Jan 2025 11:44AM UTC coverage: 67.538% (-0.003%) from 67.541%
12746499935

Pull #917

github

web-flow
Merge d5923c60e into 8e971e1a8
Pull Request #917: #916: download status code error handling

2577 of 4158 branches covered (61.98%)

Branch coverage included in aggregate %.

6671 of 9535 relevant lines covered (69.96%)

3.08 hits per line

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

64.08
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
        int statusCode = response.statusCode();
3✔
102
        if (statusCode == 200) {
3!
103
          downloadFileWithProgressBar(url, target, response);
6✔
104
        } else {
105
          throw new IllegalStateException("Download failed with status code " + statusCode);
×
106
        }
107
      } else if (url.startsWith("ftp") || url.startsWith("sftp")) {
9!
108
        throw new IllegalArgumentException("Unsupported download URL: " + url);
×
109
      } else {
110
        Path source = Path.of(url);
5✔
111
        if (isFile(source)) {
4!
112
          // network drive
113

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

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

133
    long contentLength = response.headers().firstValueAsLong("content-length").orElse(-1);
7✔
134
    informAboutMissingContentLength(contentLength, url);
4✔
135

136
    byte[] data = new byte[1024];
3✔
137
    boolean fileComplete = false;
2✔
138
    int count;
139

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

154
    } catch (Exception e) {
×
155
      throw new RuntimeException(e);
×
156
    }
1✔
157
  }
1✔
158

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

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

184
  private void informAboutMissingContentLength(long contentLength, String url) {
185

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

191
  @Override
192
  public void mkdirs(Path directory) {
193

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

205
  @Override
206
  public boolean isFile(Path file) {
207

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

219
  @Override
220
  public boolean isExpectedFolder(Path folder) {
221

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

229
  @Override
230
  public String checksum(Path file) {
231

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

250
  private boolean isJunction(Path path) {
251

252
    if (!SystemInfoImpl.INSTANCE.isWindows()) {
3!
253
      return false;
2✔
254
    }
255

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

267
  @Override
268
  public void backup(Path fileOrFolder) {
269

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

286
  @Override
287
  public void move(Path source, Path targetDir) {
288

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

302
  @Override
303
  public void copy(Path source, Path target, FileCopyMode mode, PathCopyListener listener) {
304

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

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

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

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

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

383
    assert !(isSymlink && isJunction);
5!
384

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

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

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

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

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

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

462
  @Override
463
  public void symlink(Path source, Path targetLink, boolean relative) {
464

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

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

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

496
  @Override
497
  public Path toRealPath(Path path) {
498

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

510
  @Override
511
  public Path createTempDir(String name) {
512

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

531
  @Override
532
  public void extract(Path archiveFile, Path targetDir, Consumer<Path> postExtractHook, boolean extract) {
533

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

574
  private void postExtractHook(Consumer<Path> postExtractHook, Path properInstallDir) {
575

576
    if (postExtractHook != null) {
2✔
577
      postExtractHook.accept(properInstallDir);
3✔
578
    }
579
  }
1✔
580

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

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

605
  @Override
606
  public void extractZip(Path file, Path targetDir) {
607

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

625
  @SuppressWarnings("unchecked")
626
  private void onFileCopiedFromZip(Path source, Path target, boolean directory, IdeProgressBar progressBar) {
627

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

644
  @Override
645
  public void extractTar(Path file, Path targetDir, TarCompression compression) {
646

647
    extractArchive(file, targetDir, in -> new TarArchiveInputStream(compression.unpack(in)));
13✔
648
  }
1✔
649

650
  @Override
651
  public void extractJar(Path file, Path targetDir) {
652

653
    extractZip(file, targetDir);
4✔
654
  }
1✔
655

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

662
    // Ensure that only the last 9 bits are considered
663
    permissions &= 0b111111111;
4✔
664

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

672
    return permissionStringBuilder.toString();
3✔
673
  }
674

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

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

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

714
  @Override
715
  public void extractDmg(Path file, Path targetDir) {
716

717
    this.context.info("Extracting DMG file {} to {}", file, targetDir);
×
718
    assert this.context.getSystemInfo().isMac();
×
719

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

731
    copy(appPath, targetDir, FileCopyMode.COPY_TREE_OVERRIDE_TREE);
×
732
    pc.addArgs("detach", "-force", mountPath);
×
733
    pc.run();
×
734
  }
×
735

736
  @Override
737
  public void extractMsi(Path file, Path targetDir) {
738

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

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

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

759
  @Override
760
  public void delete(Path path) {
761

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

778
  private void deleteRecursive(Path path) throws IOException {
779

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

793
  @Override
794
  public Path findFirst(Path dir, Predicate<Path> filter, boolean recursive) {
795

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

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

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

834
  @Override
835
  public List<Path> listChildren(Path dir, Predicate<Path> filter) {
836

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

858
  @Override
859
  public boolean isEmptyDir(Path dir) {
860

861
    return listChildren(dir, f -> true).isEmpty();
8✔
862
  }
863

864
  private long getFileSize(Path file) {
865

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

874
  private long getFileSizeRecursive(Path path) {
875

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

893
  @Override
894
  public Path findExistingFile(String fileName, List<Path> searchDirs) {
895

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

909
  @Override
910
  public void makeExecutable(Path file, boolean confirm) {
911

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

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

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

957
  @Override
958
  public void touch(Path file) {
959

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