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

devonfw / IDEasy / 12750410851

13 Jan 2025 03:23PM UTC coverage: 68.077% (+0.5%) from 67.541%
12750410851

Pull #820

github

web-flow
Merge b7b0d1004 into 8e971e1a8
Pull Request #820: #759: upgrade settings commandlet

2689 of 4311 branches covered (62.38%)

Branch coverage included in aggregate %.

6946 of 9842 relevant lines covered (70.58%)

3.1 hits per line

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

64.77
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 ((fileOrFolder != null) && (Files.isSymbolicLink(fileOrFolder) || isJunction(fileOrFolder))) {
9!
268
      delete(fileOrFolder);
×
269
    } else if ((fileOrFolder != null) && Files.exists(fileOrFolder)) {
7!
270
      LocalDateTime now = LocalDateTime.now();
2✔
271
      String date = DateTimeUtil.formatDate(now, true);
4✔
272
      String time = DateTimeUtil.formatTime(now);
3✔
273
      String filename = fileOrFolder.getFileName().toString();
4✔
274
      Path backupPath = this.context.getIdeHome().resolve(IdeContext.FOLDER_BACKUPS).resolve(date).resolve(time + "_" + filename);
12✔
275
      backupPath = appendParentPath(backupPath, fileOrFolder.getParent(), 2);
6✔
276
      mkdirs(backupPath);
3✔
277
      Path target = backupPath.resolve(filename);
4✔
278
      this.context.info("Creating backup by moving {} to {}", fileOrFolder, target);
14✔
279
      move(fileOrFolder, target);
4✔
280
    } else {
1✔
281
      this.context.trace("Backup of {} skipped as the path does not exist.", fileOrFolder);
10✔
282
    }
283
  }
1✔
284

285
  private static Path appendParentPath(Path path, Path parent, int max) {
286

287
    if ((parent == null) || (max <= 0)) {
4!
288
      return path;
2✔
289
    }
290
    return appendParentPath(path, parent.getParent(), max - 1).resolve(parent.getFileName());
11✔
291
  }
292

293
  @Override
294
  public void move(Path source, Path targetDir) {
295

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

309
  @Override
310
  public void copy(Path source, Path target, FileCopyMode mode, PathCopyListener listener) {
311

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

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

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

378
  /**
379
   * 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
380
   * {@link Path} that is neither a symbolic link nor a Windows junction.
381
   *
382
   * @param path the {@link Path} to delete.
383
   * @throws IOException if the actual {@link Files#delete(Path) deletion} fails.
384
   */
385
  private void deleteLinkIfExists(Path path) throws IOException {
386

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

390
    assert !(isSymlink && isJunction);
5!
391

392
    if (isJunction || isSymlink) {
4!
393
      this.context.info("Deleting previous " + (isJunction ? "junction" : "symlink") + " at " + path);
8!
394
      Files.delete(path);
2✔
395
    }
396
  }
1✔
397

398
  /**
399
   * Adapts the given {@link Path} to be relative or absolute depending on the given {@code relative} flag. Additionally, {@link Path#toRealPath(LinkOption...)}
400
   * is applied to {@code source}.
401
   *
402
   * @param source the {@link Path} to adapt.
403
   * @param targetLink the {@link Path} used to calculate the relative path to the {@code source} if {@code relative} is set to {@code true}.
404
   * @param relative the {@code relative} flag.
405
   * @return the adapted {@link Path}.
406
   * @see FileAccessImpl#symlink(Path, Path, boolean)
407
   */
408
  private Path adaptPath(Path source, Path targetLink, boolean relative) throws IOException {
409

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

438
  /**
439
   * Creates a Windows junction at {@code targetLink} pointing to {@code source}.
440
   *
441
   * @param source must be another Windows junction or a directory.
442
   * @param targetLink the location of the Windows junction.
443
   */
444
  private void createWindowsJunction(Path source, Path targetLink) {
445

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

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

469
  @Override
470
  public void symlink(Path source, Path targetLink, boolean relative) {
471

472
    Path adaptedSource = null;
2✔
473
    try {
474
      adaptedSource = adaptPath(source, targetLink, relative);
6✔
475
    } catch (IOException e) {
×
476
      throw new IllegalStateException("Failed to adapt source for source (" + source + ") target (" + targetLink + ") and relative (" + relative + ")", e);
×
477
    }
1✔
478
    this.context.trace("Creating {} symbolic link {} pointing to {}", adaptedSource.isAbsolute() ? "" : "relative", targetLink, adaptedSource);
23✔
479

480
    try {
481
      deleteLinkIfExists(targetLink);
3✔
482
    } catch (IOException e) {
×
483
      throw new IllegalStateException("Failed to delete previous symlink or Windows junction at " + targetLink, e);
×
484
    }
1✔
485

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

503
  @Override
504
  public Path toRealPath(Path path) {
505

506
    try {
507
      Path realPath = path.toRealPath();
×
508
      if (!realPath.equals(path)) {
×
509
        this.context.trace("Resolved path {} to {}", path, realPath);
×
510
      }
511
      return realPath;
×
512
    } catch (IOException e) {
×
513
      throw new IllegalStateException("Failed to get real path for " + path, e);
×
514
    }
515
  }
516

517
  @Override
518
  public Path createTempDir(String name) {
519

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

538
  @Override
539
  public void extract(Path archiveFile, Path targetDir, Consumer<Path> postExtractHook, boolean extract) {
540

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

581
  private void postExtractHook(Consumer<Path> postExtractHook, Path properInstallDir) {
582

583
    if (postExtractHook != null) {
2✔
584
      postExtractHook.accept(properInstallDir);
3✔
585
    }
586
  }
1✔
587

588
  /**
589
   * @param path the {@link Path} to start the recursive search from.
590
   * @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
591
   *     item in their respective directory and {@code s} is not named "bin".
592
   */
593
  private Path getProperInstallationSubDirOf(Path path, Path archiveFile) {
594

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

612
  @Override
613
  public void extractZip(Path file, Path targetDir) {
614

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

632
  @SuppressWarnings("unchecked")
633
  private void onFileCopiedFromZip(Path source, Path target, boolean directory, IdeProgressBar progressBar) {
634

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

651
  @Override
652
  public void extractTar(Path file, Path targetDir, TarCompression compression) {
653

654
    extractArchive(file, targetDir, in -> new TarArchiveInputStream(compression.unpack(in)));
13✔
655
  }
1✔
656

657
  @Override
658
  public void extractJar(Path file, Path targetDir) {
659

660
    extractZip(file, targetDir);
4✔
661
  }
1✔
662

663
  /**
664
   * @param permissions The integer as returned by {@link TarArchiveEntry#getMode()} that represents the file permissions of a file on a Unix file system.
665
   * @return A String representing the file permissions. E.g. "rwxrwxr-x" or "rw-rw-r--"
666
   */
667
  public static String generatePermissionString(int permissions) {
668

669
    // Ensure that only the last 9 bits are considered
670
    permissions &= 0b111111111;
4✔
671

672
    StringBuilder permissionStringBuilder = new StringBuilder("rwxrwxrwx");
5✔
673
    for (int i = 0; i < 9; i++) {
7✔
674
      int mask = 1 << i;
4✔
675
      char currentChar = ((permissions & mask) != 0) ? permissionStringBuilder.charAt(8 - i) : '-';
12✔
676
      permissionStringBuilder.setCharAt(8 - i, currentChar);
6✔
677
    }
678

679
    return permissionStringBuilder.toString();
3✔
680
  }
681

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

684
    this.context.info("Extracting TAR file {} to {}", file, targetDir);
14✔
685
    try (InputStream is = Files.newInputStream(file);
5✔
686
        ArchiveInputStream<?> ais = unpacker.apply(is);
5✔
687
        IdeProgressBar pb = this.context.newProgressbarForExtracting(getFileSize(file))) {
7✔
688

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

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

724
    this.context.info("Extracting DMG file {} to {}", file, targetDir);
×
725
    assert this.context.getSystemInfo().isMac();
×
726

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

738
    copy(appPath, targetDir, FileCopyMode.COPY_TREE_OVERRIDE_TREE);
×
739
    pc.addArgs("detach", "-force", mountPath);
×
740
    pc.run();
×
741
  }
×
742

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

746
    this.context.info("Extracting MSI file {} to {}", file, targetDir);
×
747
    this.context.newProcess().executable("msiexec").addArgs("/a", file, "/qn", "TARGETDIR=" + targetDir).run();
×
748
    // msiexec also creates a copy of the MSI
749
    Path msiCopy = targetDir.resolve(file.getFileName());
×
750
    delete(msiCopy);
×
751
  }
×
752

753
  @Override
754
  public void extractPkg(Path file, Path targetDir) {
755

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

766
  @Override
767
  public void delete(Path path) {
768

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

785
  private void deleteRecursive(Path path) throws IOException {
786

787
    if (Files.isDirectory(path)) {
5✔
788
      try (Stream<Path> childStream = Files.list(path)) {
3✔
789
        Iterator<Path> iterator = childStream.iterator();
3✔
790
        while (iterator.hasNext()) {
3✔
791
          Path child = iterator.next();
4✔
792
          deleteRecursive(child);
3✔
793
        }
1✔
794
      }
795
    }
796
    this.context.trace("Deleting {} ...", path);
10✔
797
    Files.delete(path);
2✔
798
  }
1✔
799

800
  @Override
801
  public Path findFirst(Path dir, Predicate<Path> filter, boolean recursive) {
802

803
    try {
804
      if (!Files.isDirectory(dir)) {
5✔
805
        return null;
2✔
806
      }
807
      return findFirstRecursive(dir, filter, recursive);
6✔
808
    } catch (IOException e) {
×
809
      throw new IllegalStateException("Failed to search for file in " + dir, e);
×
810
    }
811
  }
812

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

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

841
  @Override
842
  public List<Path> listChildrenMapped(Path dir, Function<Path, Path> filter) {
843

844
    if (!Files.isDirectory(dir)) {
5✔
845
      return List.of();
2✔
846
    }
847
    List<Path> children = new ArrayList<>();
4✔
848
    try (Stream<Path> childStream = Files.list(dir)) {
3✔
849
      Iterator<Path> iterator = childStream.iterator();
3✔
850
      while (iterator.hasNext()) {
3✔
851
        Path child = iterator.next();
4✔
852
        Path filteredChild = filter.apply(child);
5✔
853
        if (filteredChild != null) {
2✔
854
          if (filteredChild == child) {
3!
855
            this.context.trace("Accepted file {}", child);
11✔
856
          } else {
857
            this.context.trace("Accepted file {} and mapped to {}", child, filteredChild);
×
858
          }
859
          children.add(filteredChild);
5✔
860
        } else {
861
          this.context.trace("Ignoring file {} according to filter", child);
10✔
862
        }
863
      }
1✔
864
    } catch (IOException e) {
×
865
      throw new IllegalStateException("Failed to find children of directory " + dir, e);
×
866
    }
1✔
867
    return children;
2✔
868
  }
869

870
  @Override
871
  public boolean isEmptyDir(Path dir) {
872

873
    return listChildren(dir, f -> true).isEmpty();
8✔
874
  }
875

876
  private long getFileSize(Path file) {
877

878
    try {
879
      return Files.size(file);
3✔
880
    } catch (IOException e) {
×
881
      this.context.warning(e.getMessage(), e);
×
882
      return 0;
×
883
    }
884
  }
885

886
  private long getFileSizeRecursive(Path path) {
887

888
    long size = 0;
2✔
889
    if (Files.isDirectory(path)) {
5✔
890
      try (Stream<Path> childStream = Files.list(path)) {
3✔
891
        Iterator<Path> iterator = childStream.iterator();
3✔
892
        while (iterator.hasNext()) {
3✔
893
          Path child = iterator.next();
4✔
894
          size += getFileSizeRecursive(child);
6✔
895
        }
1✔
896
      } catch (IOException e) {
×
897
        throw new RuntimeException("Failed to iterate children of folder " + path, e);
×
898
      }
1✔
899
    } else {
900
      size += getFileSize(path);
6✔
901
    }
902
    return size;
2✔
903
  }
904

905
  @Override
906
  public Path findExistingFile(String fileName, List<Path> searchDirs) {
907

908
    for (Path dir : searchDirs) {
10!
909
      Path filePath = dir.resolve(fileName);
4✔
910
      try {
911
        if (Files.exists(filePath)) {
5!
912
          return filePath;
2✔
913
        }
914
      } catch (Exception e) {
×
915
        throw new IllegalStateException("Unexpected error while checking existence of file " + filePath + " .", e);
×
916
      }
×
917
    }
×
918
    return null;
×
919
  }
920

921
  @Override
922
  public void makeExecutable(Path file, boolean confirm) {
923

924
    if (Files.exists(file)) {
5✔
925
      if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
926
        this.context.trace("Windows does not have executable flags hence omitting for file {}", file);
×
927
        return;
×
928
      }
929
      try {
930
        // Read the current file permissions
931
        Set<PosixFilePermission> existingPermissions = Files.getPosixFilePermissions(file);
5✔
932

933
        // Add execute permission for all users
934
        Set<PosixFilePermission> executablePermissions = new HashSet<>(existingPermissions);
5✔
935
        boolean update = false;
2✔
936
        update |= executablePermissions.add(PosixFilePermission.OWNER_EXECUTE);
6✔
937
        update |= executablePermissions.add(PosixFilePermission.GROUP_EXECUTE);
6✔
938
        update |= executablePermissions.add(PosixFilePermission.OTHERS_EXECUTE);
6✔
939

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

969
  @Override
970
  public void touch(Path file) {
971

972
    if (Files.exists(file)) {
5✔
973
      try {
974
        Files.setLastModifiedTime(file, FileTime.fromMillis(System.currentTimeMillis()));
5✔
975
      } catch (IOException e) {
×
976
        throw new IllegalStateException("Could not update modification-time of " + file, e);
×
977
      }
1✔
978
    } else {
979
      try {
980
        Files.createFile(file);
5✔
981
      } catch (IOException e) {
1✔
982
        throw new IllegalStateException("Could not create empty file " + file, e);
7✔
983
      }
1✔
984
    }
985
  }
1✔
986
}
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