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

devonfw / IDEasy / 13055946744

30 Jan 2025 03:47PM UTC coverage: 68.557% (+0.1%) from 68.45%
13055946744

push

github

web-flow
#993: create IDE start scripts (#994)

Co-authored-by: jan-vcapgemini <59438728+jan-vcapgemini@users.noreply.github.com>

2809 of 4495 branches covered (62.49%)

Branch coverage included in aggregate %.

7260 of 10192 relevant lines covered (71.23%)

3.1 hits per line

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

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

288
  private static Path appendParentPath(Path path, Path parent, int max) {
289

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

296
  @Override
297
  public void move(Path source, Path targetDir) {
298

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

312
  @Override
313
  public void copy(Path source, Path target, FileCopyMode mode, PathCopyListener listener) {
314

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

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

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

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

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

393
    assert !(isSymlink && isJunction);
5!
394

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

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

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

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

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

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

472
  @Override
473
  public void symlink(Path source, Path targetLink, boolean relative) {
474

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

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

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

506
  @Override
507
  public Path toRealPath(Path path) {
508

509
    try {
510
      Path realPath = path.toRealPath();
5✔
511
      if (!realPath.equals(path)) {
4✔
512
        this.context.trace("Resolved path {} to {}", path, realPath);
14✔
513
      }
514
      return realPath;
2✔
515
    } catch (IOException e) {
×
516
      throw new IllegalStateException("Failed to get real path for " + path, e);
×
517
    }
518
  }
519

520
  @Override
521
  public Path createTempDir(String name) {
522

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

541
  @Override
542
  public void extract(Path archiveFile, Path targetDir, Consumer<Path> postExtractHook, boolean extract) {
543

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

584
  private void postExtractHook(Consumer<Path> postExtractHook, Path properInstallDir) {
585

586
    if (postExtractHook != null) {
2✔
587
      postExtractHook.accept(properInstallDir);
3✔
588
    }
589
  }
1✔
590

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

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

615
  @Override
616
  public void extractZip(Path file, Path targetDir) {
617

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

635
  @SuppressWarnings("unchecked")
636
  private void onFileCopiedFromZip(Path source, Path target, boolean directory, IdeProgressBar progressBar) {
637

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

654
  @Override
655
  public void extractTar(Path file, Path targetDir, TarCompression compression) {
656

657
    extractArchive(file, targetDir, in -> new TarArchiveInputStream(compression.unpack(in)));
13✔
658
  }
1✔
659

660
  @Override
661
  public void extractJar(Path file, Path targetDir) {
662

663
    extractZip(file, targetDir);
4✔
664
  }
1✔
665

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

672
    // Ensure that only the last 9 bits are considered
673
    permissions &= 0b111111111;
4✔
674

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

682
    return permissionStringBuilder.toString();
3✔
683
  }
684

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

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

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

724
  @Override
725
  public void extractDmg(Path file, Path targetDir) {
726

727
    this.context.info("Extracting DMG file {} to {}", file, targetDir);
×
728
    assert this.context.getSystemInfo().isMac();
×
729

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

741
    copy(appPath, targetDir, FileCopyMode.COPY_TREE_OVERRIDE_TREE);
×
742
    pc.addArgs("detach", "-force", mountPath);
×
743
    pc.run();
×
744
  }
×
745

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

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

756
  @Override
757
  public void extractPkg(Path file, Path targetDir) {
758

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

769
  @Override
770
  public void delete(Path path) {
771

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

788
  private void deleteRecursive(Path path) throws IOException {
789

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

803
  @Override
804
  public Path findFirst(Path dir, Predicate<Path> filter, boolean recursive) {
805

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

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

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

844
  @Override
845
  public List<Path> listChildrenMapped(Path dir, Function<Path, Path> filter) {
846

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

873
  @Override
874
  public boolean isEmptyDir(Path dir) {
875

876
    return listChildren(dir, f -> true).isEmpty();
8✔
877
  }
878

879
  private long getFileSize(Path file) {
880

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

889
  private long getFileSizeRecursive(Path path) {
890

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

908
  @Override
909
  public Path findExistingFile(String fileName, List<Path> searchDirs) {
910

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

924
  @Override
925
  public void makeExecutable(Path file, boolean confirm) {
926

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

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

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

972
  @Override
973
  public void touch(Path file) {
974

975
    if (Files.exists(file)) {
5✔
976
      try {
977
        Files.setLastModifiedTime(file, FileTime.fromMillis(System.currentTimeMillis()));
5✔
978
      } catch (IOException e) {
×
979
        throw new IllegalStateException("Could not update modification-time of " + file, e);
×
980
      }
1✔
981
    } else {
982
      try {
983
        Files.createFile(file);
5✔
984
      } catch (IOException e) {
1✔
985
        throw new IllegalStateException("Could not create empty file " + file, e);
8✔
986
      }
1✔
987
    }
988
  }
1✔
989

990
  @Override
991
  public String readFileContent(Path file) {
992

993
    this.context.trace("Reading content of file from {}", file);
10✔
994
    try {
995
      String content = Files.readString(file);
3✔
996
      this.context.trace("Read content of length {} from file {}", content.length(), file);
16✔
997
      return content;
2✔
998
    } catch (IOException e) {
×
999
      throw new IllegalStateException("Failed to read file " + file, e);
×
1000
    }
1001
  }
1002

1003
  @Override
1004
  public void writeFileContent(String content, Path file) {
1005

1006
    if (content == null) {
2!
1007
      content = "";
×
1008
    }
1009
    this.context.trace("Writing content with length {} to file {}", content.length(), file);
16✔
1010
    if (Files.exists(file)) {
5!
1011
      this.context.info("Overriding content of file {}", file);
×
1012
    }
1013
    try {
1014
      Files.writeString(file, content);
6✔
1015
      this.context.trace("Wrote content to file {}", file);
10✔
1016
    } catch (IOException e) {
×
1017
      throw new RuntimeException("Failed to write file " + file, e);
×
1018
    }
1✔
1019
  }
1✔
1020
}
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