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

devonfw / IDEasy / 25334060192

04 May 2026 05:46PM UTC coverage: 70.657% (+0.01%) from 70.645%
25334060192

Pull #1879

github

web-flow
Merge f8915bc1c into fa3a8b3c5
Pull Request #1879: #1844: Fix VSCode plugin installation progress freezing

4386 of 6856 branches covered (63.97%)

Branch coverage included in aggregate %.

11309 of 15357 relevant lines covered (73.64%)

3.11 hits per line

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

81.21
cli/src/main/java/com/devonfw/tools/ide/process/ProcessContextImpl.java
1
package com.devonfw.tools.ide.process;
2

3
import java.io.BufferedReader;
4
import java.io.IOException;
5
import java.io.InputStream;
6
import java.io.InputStreamReader;
7
import java.lang.ProcessBuilder.Redirect;
8
import java.nio.charset.StandardCharsets;
9
import java.nio.file.Files;
10
import java.nio.file.Path;
11
import java.util.ArrayList;
12
import java.util.List;
13
import java.util.Map;
14
import java.util.Objects;
15
import java.util.concurrent.CompletableFuture;
16
import java.util.concurrent.ConcurrentLinkedQueue;
17
import java.util.function.Predicate;
18
import java.util.stream.Collectors;
19

20
import org.slf4j.Logger;
21
import org.slf4j.LoggerFactory;
22

23
import com.devonfw.tools.ide.cli.CliProcessException;
24
import com.devonfw.tools.ide.common.SystemPath;
25
import com.devonfw.tools.ide.context.IdeContext;
26
import com.devonfw.tools.ide.environment.VariableLine;
27
import com.devonfw.tools.ide.log.IdeLogLevel;
28
import com.devonfw.tools.ide.os.SystemInfoImpl;
29
import com.devonfw.tools.ide.os.WindowsPathSyntax;
30
import com.devonfw.tools.ide.util.FilenameUtil;
31
import com.devonfw.tools.ide.variable.IdeVariables;
32

33
/**
34
 * Implementation of {@link ProcessContext}.
35
 */
36
public class ProcessContextImpl implements ProcessContext {
37

38
  private static final Logger LOG = LoggerFactory.getLogger(ProcessContextImpl.class);
3✔
39

40
  private static final String PREFIX_USR_BIN_ENV = "/usr/bin/env ";
41
  private static final Predicate<Integer> EXIT_CODE_ACCEPTOR = rc -> rc == ProcessResult.SUCCESS;
10✔
42

43
  /** The owning {@link IdeContext}. */
44
  protected final IdeContext context;
45

46
  private final ProcessBuilder processBuilder;
47

48
  protected final List<String> arguments;
49

50
  protected Path executable;
51

52
  private String overriddenPath;
53

54
  private final List<Path> extraPathEntries;
55

56
  private ProcessErrorHandling errorHandling;
57

58
  private OutputListener outputListener;
59

60
  private Predicate<Integer> exitCodeAcceptor;
61

62
  /**
63
   * The constructor.
64
   *
65
   * @param context the owning {@link IdeContext}.
66
   */
67
  public ProcessContextImpl(IdeContext context) {
68

69
    super();
2✔
70
    this.context = context;
3✔
71
    this.processBuilder = new ProcessBuilder();
7✔
72
    this.errorHandling = ProcessErrorHandling.THROW_ERR;
3✔
73
    Map<String, String> environment = this.processBuilder.environment();
4✔
74
    for (VariableLine var : this.context.getVariables().collectExportedVariables()) {
13✔
75
      if (var.isExport()) {
3!
76
        environment.put(var.getName(), var.getValue());
7✔
77
      }
78
    }
1✔
79
    this.arguments = new ArrayList<>();
5✔
80
    this.extraPathEntries = new ArrayList<>();
5✔
81
    this.exitCodeAcceptor = EXIT_CODE_ACCEPTOR;
3✔
82
  }
1✔
83

84
  private ProcessContextImpl(ProcessContextImpl parent) {
85

86
    super();
×
87
    this.context = parent.context;
×
88
    this.processBuilder = parent.processBuilder;
×
89
    this.errorHandling = ProcessErrorHandling.THROW_ERR;
×
90
    this.arguments = new ArrayList<>();
×
91
    this.extraPathEntries = parent.extraPathEntries;
×
92
    this.exitCodeAcceptor = EXIT_CODE_ACCEPTOR;
×
93
  }
×
94

95
  @Override
96
  public ProcessContext errorHandling(ProcessErrorHandling handling) {
97

98
    Objects.requireNonNull(handling);
3✔
99
    this.errorHandling = handling;
3✔
100
    return this;
2✔
101
  }
102

103
  @Override
104
  public ProcessContext directory(Path directory) {
105

106
    if (directory != null) {
2!
107
      this.processBuilder.directory(directory.toFile());
7✔
108
    } else {
109
      LOG.debug(
×
110
          "Could not set the process builder's working directory! Directory of the current java process is used.");
111
    }
112

113
    return this;
2✔
114
  }
115

116
  @Override
117
  public ProcessContext executable(Path command) {
118

119
    if (!this.arguments.isEmpty()) {
4!
120
      throw new IllegalStateException("Arguments already present - did you forget to call run for previous call?");
×
121
    }
122

123
    this.executable = command;
3✔
124
    return this;
2✔
125
  }
126

127
  @Override
128
  public ProcessContext addArg(String arg) {
129

130
    this.arguments.add(arg);
5✔
131
    return this;
2✔
132
  }
133

134
  @Override
135
  public ProcessContext withEnvVar(String key, String value) {
136

137
    if (IdeVariables.PATH.getName().equals(key)) {
5!
138
      this.overriddenPath = value;
×
139
    } else {
140
      LOG.trace("Setting process environment variable {}={}", key, value);
5✔
141
      this.processBuilder.environment().put(key, value);
7✔
142
    }
143
    return this;
2✔
144
  }
145

146
  @Override
147
  public ProcessContext withPathEntry(Path path) {
148

149
    this.extraPathEntries.add(path);
5✔
150
    return this;
2✔
151
  }
152

153
  @Override
154
  public ProcessContext withExitCodeAcceptor(Predicate<Integer> exitCodeAcceptor) {
155

156
    this.exitCodeAcceptor = exitCodeAcceptor;
3✔
157
    return this;
2✔
158
  }
159

160
  @Override
161
  public ProcessContext createChild() {
162

163
    return new ProcessContextImpl(this);
×
164
  }
165

166
  @Override
167
  public void setOutputListener(OutputListener listener) {
168
    this.outputListener = listener;
3✔
169
  }
1✔
170

171
  @Override
172
  public ProcessResult run(ProcessMode processMode) {
173

174
    if (this.executable == null) {
3✔
175
      throw new IllegalStateException("Missing executable to run process!");
5✔
176
    }
177

178
    SystemPath systemPath = this.context.getPath();
4✔
179
    if ((this.overriddenPath != null) || !this.extraPathEntries.isEmpty()) {
7!
180
      systemPath = systemPath.withPath(this.overriddenPath, this.extraPathEntries);
7✔
181
    }
182
    String path = systemPath.toString();
3✔
183
    LOG.trace("Setting PATH for process execution of {} to {}", this.executable.getFileName(), path);
7✔
184
    this.executable = systemPath.findBinary(this.executable);
6✔
185
    this.processBuilder.environment().put(IdeVariables.PATH.getName(), path);
8✔
186
    List<String> args = new ArrayList<>(this.arguments.size() + 4);
9✔
187
    String interpreter = addExecutable(args);
4✔
188
    args.addAll(this.arguments);
5✔
189
    String command = createCommand();
3✔
190
    if (LOG.isDebugEnabled()) {
3!
191
      String message = createCommandMessage(interpreter, " ...");
5✔
192
      LOG.debug(message);
3✔
193
    }
194

195
    try {
196
      applyRedirects(processMode);
3✔
197
      if (processMode.isBackground()) {
3✔
198
        modifyArgumentsOnBackgroundProcess(processMode);
3✔
199
      }
200

201
      this.processBuilder.command(args);
5✔
202

203
      ConcurrentLinkedQueue<OutputMessage> output = new ConcurrentLinkedQueue<>();
4✔
204

205
      Process process = this.processBuilder.start();
4✔
206

207
      try {
208
        if (Redirect.PIPE == processMode.getRedirectOutput() || Redirect.PIPE == processMode.getRedirectError()) {
8!
209
          CompletableFuture<Void> outFut = readInputStream(process.getInputStream(), false, output);
6✔
210
          CompletableFuture<Void> errFut = readInputStream(process.getErrorStream(), true, output);
6✔
211
          if (Redirect.PIPE == processMode.getRedirectOutput()) {
4!
212
            outFut.get();
3✔
213
          }
214
          if (Redirect.PIPE == processMode.getRedirectError()) {
4!
215
            errFut.get();
3✔
216
          }
217
          if (this.outputListener != null) {
3✔
218
            for (OutputMessage msg : output) {
10✔
219
              this.outputListener.onOutput(msg.message(), msg.error());
7✔
220
            }
1✔
221
          }
222
        }
223

224
        int exitCode;
225

226
        if (processMode.isBackground()) {
3✔
227
          exitCode = ProcessResult.SUCCESS;
3✔
228
        } else {
229
          exitCode = process.waitFor();
3✔
230
        }
231

232
        List<OutputMessage> finalOutput = new ArrayList<>(output);
5✔
233
        boolean success = this.exitCodeAcceptor.test(exitCode);
6✔
234
        ProcessResult result = new ProcessResultImpl(this.executable.getFileName().toString(), command, exitCode, success, finalOutput);
12✔
235

236
        performLogging(result, exitCode, interpreter);
5✔
237

238
        return result;
4✔
239
      } finally {
240
        if (!processMode.isBackground()) {
3✔
241
          process.destroy();
2✔
242
        }
243
      }
244
    } catch (CliProcessException | IllegalStateException e) {
1✔
245
      // these exceptions are thrown from performLogOnError and we do not want to wrap them (see #593)
246
      throw e;
2✔
247
    } catch (Exception e) {
1✔
248
      String msg = e.getMessage();
3✔
249
      if ((msg == null) || msg.isEmpty()) {
5!
250
        msg = e.getClass().getSimpleName();
×
251
      }
252
      throw new IllegalStateException(createCommandMessage(interpreter, " failed: " + msg), e);
10✔
253
    } finally {
254
      this.arguments.clear();
3✔
255
    }
256
  }
257

258
  /**
259
   * Asynchronously and parallel reads {@link InputStream input stream} and stores it in {@link CompletableFuture}. Inspired by: <a href=
260
   * "https://stackoverflow.com/questions/14165517/processbuilder-forwarding-stdout-and-stderr-of-started-processes-without-blocki/57483714#57483714">StackOverflow</a>
261
   *
262
   * @param is {@link InputStream}.
263
   * @param errorStream to identify if the output came from stdout or stderr
264
   * @return {@link CompletableFuture}.
265
   */
266
  private static CompletableFuture<Void> readInputStream(InputStream is, boolean errorStream, ConcurrentLinkedQueue<OutputMessage> outputMessages) {
267

268
    return CompletableFuture.supplyAsync(() -> {
6✔
269

270
      try (InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr)) {
10✔
271

272
        String line;
273
        while ((line = br.readLine()) != null) {
5✔
274
          OutputMessage outputMessage = new OutputMessage(errorStream, line);
6✔
275
          outputMessages.add(outputMessage);
4✔
276
        }
1✔
277

278
        return null;
4✔
279
      } catch (Throwable e) {
1✔
280
        throw new RuntimeException("There was a problem while executing the program", e);
6✔
281
      }
282
    });
283
  }
284

285
  private String createCommand() {
286
    String cmd = this.executable.toString();
4✔
287
    StringBuilder sb = new StringBuilder(cmd.length() + this.arguments.size() * 4);
12✔
288
    sb.append(cmd);
4✔
289
    for (String arg : this.arguments) {
11✔
290
      sb.append(' ');
4✔
291
      sb.append(arg);
4✔
292
    }
1✔
293
    return sb.toString();
3✔
294
  }
295

296
  private String createCommandMessage(String interpreter, String suffix) {
297

298
    StringBuilder sb = new StringBuilder();
4✔
299
    sb.append("Running command '");
4✔
300
    sb.append(this.executable);
5✔
301
    sb.append("'");
4✔
302
    if (interpreter != null) {
2✔
303
      sb.append(" using ");
4✔
304
      sb.append(interpreter);
4✔
305
    }
306
    int size = this.arguments.size();
4✔
307
    if (size > 0) {
2✔
308
      sb.append(" with arguments");
4✔
309
      for (int i = 0; i < size; i++) {
7✔
310
        String arg = this.arguments.get(i);
6✔
311
        sb.append(" '");
4✔
312
        sb.append(arg);
4✔
313
        sb.append("'");
4✔
314
      }
315
    }
316
    sb.append(suffix);
4✔
317
    return sb.toString();
3✔
318
  }
319

320
  private String getSheBang(Path file) {
321

322
    try (InputStream in = Files.newInputStream(file)) {
5✔
323
      // "#!/usr/bin/env bash".length() = 19
324
      byte[] buffer = new byte[32];
3✔
325
      int read = in.read(buffer);
4✔
326
      if ((read > 2) && (buffer[0] == '#') && (buffer[1] == '!')) {
13!
327
        int start = 2;
2✔
328
        int end = 2;
2✔
329
        while (end < read) {
3!
330
          byte c = buffer[end];
4✔
331
          if ((c == '\n') || (c == '\r') || (c > 127)) {
9!
332
            break;
×
333
          } else if ((end == start) && (c == ' ')) {
6!
334
            start++;
×
335
          }
336
          end++;
1✔
337
        }
1✔
338
        String sheBang = new String(buffer, start, end - start, StandardCharsets.US_ASCII).trim();
11✔
339
        if (sheBang.startsWith(PREFIX_USR_BIN_ENV)) {
4✔
340
          sheBang = sheBang.substring(PREFIX_USR_BIN_ENV.length());
5✔
341
        }
342
        return sheBang;
4✔
343
      }
344
    } catch (IOException e) {
5!
345
      // ignore...
346
    }
1✔
347
    return null;
2✔
348
  }
349

350
  private String addExecutable(List<String> args) {
351

352
    String interpreter = null;
2✔
353
    String fileExtension = FilenameUtil.getExtension(this.executable.getFileName().toString());
6✔
354
    boolean isBashScript = "sh".equals(fileExtension);
4✔
355
    this.context.getFileAccess().makeExecutable(this.executable, true);
7✔
356
    if (!isBashScript) {
2✔
357
      String sheBang = getSheBang(this.executable);
5✔
358
      if (sheBang != null) {
2✔
359
        String cmd = sheBang;
2✔
360
        int lastSlash = cmd.lastIndexOf('/');
4✔
361
        if (lastSlash >= 0) {
2✔
362
          cmd = cmd.substring(lastSlash + 1);
6✔
363
        }
364
        if (cmd.equals("bash")) {
4!
365
          isBashScript = true;
2✔
366
        } else {
367
          // currently we do not support other interpreters...
368
        }
369
      }
370
    }
371
    if (isBashScript) {
2✔
372
      interpreter = "bash";
2✔
373
      args.add(this.context.findBashRequired().toString());
7✔
374
    }
375
    if ("msi".equalsIgnoreCase(fileExtension)) {
4!
376
      args.addFirst("/i");
×
377
      args.addFirst("msiexec");
×
378
    }
379
    args.add(this.executable.toString());
6✔
380
    return interpreter;
2✔
381
  }
382

383
  private void performLogging(ProcessResult result, int exitCode, String interpreter) {
384

385
    if (!result.isSuccessful() && (this.errorHandling != ProcessErrorHandling.NONE)) {
7!
386
      IdeLogLevel ideLogLevel = this.errorHandling.getLogLevel();
4✔
387
      String message = createCommandMessage(interpreter, "\nfailed with exit code " + exitCode + "!");
6✔
388

389
      LOG.atLevel(ideLogLevel.getSlf4jLevel()).log(message);
6✔
390
      result.log(ideLogLevel);
3✔
391

392
      if (this.errorHandling == ProcessErrorHandling.THROW_CLI) {
4!
393
        throw new CliProcessException(message, result);
×
394
      } else if (this.errorHandling == ProcessErrorHandling.THROW_ERR) {
4✔
395
        throw new IllegalStateException(message);
5✔
396
      }
397
    }
398
  }
1✔
399

400
  private void modifyArgumentsOnBackgroundProcess(ProcessMode processMode) {
401

402
    assert processMode.isBackground() : "Cannot handle non background process mode!";
4!
403

404
    Path bash = this.context.findBash();
4✔
405
    if (bash == null) {
2!
406
      LOG.warn("Cannot start background process via bash because no bash installation was found. Hence, output will be discarded.");
×
407
      this.processBuilder.redirectOutput(Redirect.DISCARD).redirectError(Redirect.DISCARD);
×
408
      return;
×
409
    }
410

411
    String commandToRunInBackground = buildCommandToRunInBackground();
3✔
412

413
    this.arguments.clear();
3✔
414
    this.arguments.add(bash.toString());
6✔
415
    this.arguments.add("-c");
5✔
416
    commandToRunInBackground += " & disown";
3✔
417
    this.arguments.add(commandToRunInBackground);
5✔
418

419
  }
1✔
420

421
  private void applyRedirects(ProcessMode processMode) {
422

423
    Redirect output = processMode.getRedirectOutput();
3✔
424
    Redirect error = processMode.getRedirectError();
3✔
425
    Redirect input = processMode.getRedirectInput();
3✔
426

427
    if (output != null) {
2!
428
      this.processBuilder.redirectOutput(output);
5✔
429
    }
430
    if (error != null) {
2!
431
      this.processBuilder.redirectError(error);
5✔
432
    }
433
    if (input != null) {
2✔
434
      this.processBuilder.redirectInput(input);
5✔
435
    }
436
  }
1✔
437

438
  private String buildCommandToRunInBackground() {
439

440
    if (this.context.getSystemInfo().isWindows()) {
5!
441

442
      StringBuilder stringBuilder = new StringBuilder();
×
443

444
      for (String argument : this.arguments) {
×
445

446
        if (SystemInfoImpl.INSTANCE.isWindows() && SystemPath.isValidWindowsPath(argument)) {
×
447
          argument = WindowsPathSyntax.MSYS.normalize(argument);
×
448
        }
449

450
        stringBuilder.append(argument);
×
451
        stringBuilder.append(" ");
×
452
      }
×
453
      return stringBuilder.toString().trim();
×
454
    } else {
455
      return this.arguments.stream().map(Object::toString).collect(Collectors.joining(" "));
10✔
456
    }
457
  }
458
}
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