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

devonfw / IDEasy / 13206540769

07 Feb 2025 07:17PM UTC coverage: 68.469% (+0.09%) from 68.379%
13206540769

push

github

web-flow
#982: ability for user specific workspace configuration templates (#1010)

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

2863 of 4595 branches covered (62.31%)

Branch coverage included in aggregate %.

7393 of 10384 relevant lines covered (71.2%)

3.1 hits per line

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

65.13
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.io.Reader;
10
import java.io.Writer;
11
import java.net.URI;
12
import java.net.http.HttpClient;
13
import java.net.http.HttpClient.Redirect;
14
import java.net.http.HttpRequest;
15
import java.net.http.HttpResponse;
16
import java.nio.file.FileSystem;
17
import java.nio.file.FileSystemException;
18
import java.nio.file.FileSystems;
19
import java.nio.file.Files;
20
import java.nio.file.LinkOption;
21
import java.nio.file.NoSuchFileException;
22
import java.nio.file.Path;
23
import java.nio.file.attribute.BasicFileAttributes;
24
import java.nio.file.attribute.FileTime;
25
import java.nio.file.attribute.PosixFilePermission;
26
import java.nio.file.attribute.PosixFilePermissions;
27
import java.security.DigestInputStream;
28
import java.security.MessageDigest;
29
import java.security.NoSuchAlgorithmException;
30
import java.time.LocalDateTime;
31
import java.util.ArrayList;
32
import java.util.HashSet;
33
import java.util.Iterator;
34
import java.util.List;
35
import java.util.Map;
36
import java.util.Properties;
37
import java.util.Set;
38
import java.util.function.Consumer;
39
import java.util.function.Function;
40
import java.util.function.Predicate;
41
import java.util.stream.Stream;
42

43
import org.apache.commons.compress.archivers.ArchiveEntry;
44
import org.apache.commons.compress.archivers.ArchiveInputStream;
45
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
46
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
47

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

58
/**
59
 * Implementation of {@link FileAccess}.
60
 */
61
public class FileAccessImpl implements FileAccess {
62

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

65
  private static final String WINDOWS_FILE_LOCK_WARNING =
66
      "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"
67
          + WINDOWS_FILE_LOCK_DOCUMENTATION_PAGE;
68

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

71
  private final IdeContext context;
72

73
  /**
74
   * The constructor.
75
   *
76
   * @param context the {@link IdeContext} to use.
77
   */
78
  public FileAccessImpl(IdeContext context) {
79

80
    super();
2✔
81
    this.context = context;
3✔
82
  }
1✔
83

84
  private HttpClient createHttpClient(String url) {
85

86
    HttpClient.Builder builder = HttpClient.newBuilder().followRedirects(Redirect.ALWAYS);
4✔
87
    return builder.build();
3✔
88
  }
89

90
  @Override
91
  public void download(String url, Path target) {
92

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

101
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)).GET().build();
7✔
102
        HttpClient client = createHttpClient(url);
4✔
103
        HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
5✔
104
        int statusCode = response.statusCode();
3✔
105
        if (statusCode == 200) {
3!
106
          downloadFileWithProgressBar(url, target, response);
6✔
107
        } else {
108
          throw new IllegalStateException("Download failed with status code " + statusCode);
×
109
        }
110
      } else if (url.startsWith("ftp") || url.startsWith("sftp")) {
9!
111
        throw new IllegalArgumentException("Unsupported download URL: " + url);
×
112
      } else {
113
        Path source = Path.of(url);
5✔
114
        if (isFile(source)) {
4!
115
          // network drive
116

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

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

136
    long contentLength = response.headers().firstValueAsLong("content-length").orElse(-1);
7✔
137
    informAboutMissingContentLength(contentLength, url);
4✔
138

139
    byte[] data = new byte[1024];
3✔
140
    boolean fileComplete = false;
2✔
141
    int count;
142

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

157
    } catch (Exception e) {
×
158
      throw new RuntimeException(e);
×
159
    }
1✔
160
  }
1✔
161

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

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

187
  private void informAboutMissingContentLength(long contentLength, String url) {
188

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

194
  @Override
195
  public void mkdirs(Path directory) {
196

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

208
  @Override
209
  public boolean isFile(Path file) {
210

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

222
  @Override
223
  public boolean isExpectedFolder(Path folder) {
224

225
    if (Files.isDirectory(folder)) {
5!
226
      return true;
2✔
227
    }
228
    this.context.warning("Expected folder was not found at {}", folder);
×
229
    return false;
×
230
  }
231

232
  @Override
233
  public String checksum(Path file) {
234

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

253
  public boolean isJunction(Path path) {
254

255
    if (!SystemInfoImpl.INSTANCE.isWindows()) {
3!
256
      return false;
2✔
257
    }
258

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

270
  @Override
271
  public void backup(Path fileOrFolder) {
272

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

291
  private static Path appendParentPath(Path path, Path parent, int max) {
292

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

299
  @Override
300
  public void move(Path source, Path targetDir) {
301

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

315
  @Override
316
  public void copy(Path source, Path target, FileCopyMode mode, PathCopyListener listener) {
317

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

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

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

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

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

396
    assert !(isSymlink && isJunction);
5!
397

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

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

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

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

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

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

475
  @Override
476
  public void symlink(Path source, Path targetLink, boolean relative) {
477

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

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

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

509
  @Override
510
  public Path toRealPath(Path path) {
511

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

523
  @Override
524
  public Path createTempDir(String name) {
525

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

544
  @Override
545
  public void extract(Path archiveFile, Path targetDir, Consumer<Path> postExtractHook, boolean extract) {
546

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

587
  private void postExtractHook(Consumer<Path> postExtractHook, Path properInstallDir) {
588

589
    if (postExtractHook != null) {
2✔
590
      postExtractHook.accept(properInstallDir);
3✔
591
    }
592
  }
1✔
593

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

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

618
  @Override
619
  public void extractZip(Path file, Path targetDir) {
620

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

638
  @SuppressWarnings("unchecked")
639
  private void onFileCopiedFromZip(Path source, Path target, boolean directory, IdeProgressBar progressBar) {
640

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

657
  @Override
658
  public void extractTar(Path file, Path targetDir, TarCompression compression) {
659

660
    extractArchive(file, targetDir, in -> new TarArchiveInputStream(compression.unpack(in)));
13✔
661
  }
1✔
662

663
  @Override
664
  public void extractJar(Path file, Path targetDir) {
665

666
    extractZip(file, targetDir);
4✔
667
  }
1✔
668

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

675
    // Ensure that only the last 9 bits are considered
676
    permissions &= 0b111111111;
4✔
677

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

685
    return permissionStringBuilder.toString();
3✔
686
  }
687

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

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

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

727
  @Override
728
  public void extractDmg(Path file, Path targetDir) {
729

730
    this.context.info("Extracting DMG file {} to {}", file, targetDir);
×
731
    assert this.context.getSystemInfo().isMac();
×
732

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

744
    copy(appPath, targetDir, FileCopyMode.COPY_TREE_OVERRIDE_TREE);
×
745
    pc.addArgs("detach", "-force", mountPath);
×
746
    pc.run();
×
747
  }
×
748

749
  @Override
750
  public void extractMsi(Path file, Path targetDir) {
751

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

759
  @Override
760
  public void extractPkg(Path file, Path targetDir) {
761

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

772
  @Override
773
  public void delete(Path path) {
774

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

791
  private void deleteRecursive(Path path) throws IOException {
792

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

806
  @Override
807
  public Path findFirst(Path dir, Predicate<Path> filter, boolean recursive) {
808

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

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

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

847
  @Override
848
  public List<Path> listChildrenMapped(Path dir, Function<Path, Path> filter) {
849

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

876
  @Override
877
  public boolean isEmptyDir(Path dir) {
878

879
    return listChildren(dir, f -> true).isEmpty();
8✔
880
  }
881

882
  private long getFileSize(Path file) {
883

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

892
  private long getFileSizeRecursive(Path path) {
893

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

911
  @Override
912
  public Path findExistingFile(String fileName, List<Path> searchDirs) {
913

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

927
  @Override
928
  public void makeExecutable(Path file, boolean confirm) {
929

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

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

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

975
  @Override
976
  public void touch(Path file) {
977

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

993
  @Override
994
  public String readFileContent(Path file) {
995

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

1006
  @Override
1007
  public void writeFileContent(String content, Path file, boolean createParentDir) {
1008

1009
    if (createParentDir) {
2!
1010
      mkdirs(file.getParent());
×
1011
    }
1012
    if (content == null) {
2!
1013
      content = "";
×
1014
    }
1015
    this.context.trace("Writing content with length {} to file {}", content.length(), file);
16✔
1016
    if (Files.exists(file)) {
5!
1017
      this.context.info("Overriding content of file {}", file);
×
1018
    }
1019
    try {
1020
      Files.writeString(file, content);
6✔
1021
      this.context.trace("Wrote content to file {}", file);
10✔
1022
    } catch (IOException e) {
×
1023
      throw new RuntimeException("Failed to write file " + file, e);
×
1024
    }
1✔
1025
  }
1✔
1026

1027
  @Override
1028
  public void readProperties(Path file, Properties properties) {
1029

1030
    try (Reader reader = Files.newBufferedReader(file)) {
3✔
1031
      properties.load(reader);
3✔
1032
      this.context.debug("Successfully loaded {} properties from {}", properties.size(), file);
16✔
1033
    } catch (IOException e) {
×
1034
      throw new IllegalStateException("Failed to read properties file: " + file, e);
×
1035
    }
1✔
1036
  }
1✔
1037

1038
  @Override
1039
  public void writeProperties(Properties properties, Path file, boolean createParentDir) {
1040

1041
    if (createParentDir) {
2✔
1042
      mkdirs(file.getParent());
4✔
1043
    }
1044
    try (Writer writer = Files.newBufferedWriter(file)) {
5✔
1045
      properties.store(writer, null); // do not get confused - Java still writes a date/time header that cannot be omitted
4✔
1046
      this.context.debug("Successfully saved {} properties to {}", properties.size(), file);
16✔
1047
    } catch (IOException e) {
×
1048
      throw new IllegalStateException("Failed to save properties file during tests.", e);
×
1049
    }
1✔
1050
  }
1✔
1051
}
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