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

devonfw / IDEasy / 22317391561

23 Feb 2026 05:30PM UTC coverage: 70.257% (-0.2%) from 70.474%
22317391561

Pull #1714

github

web-flow
Merge 5be048514 into 379acdc9d
Pull Request #1714: #404: #1713: advanced logging

4066 of 6384 branches covered (63.69%)

Branch coverage included in aggregate %.

10598 of 14488 relevant lines covered (73.15%)

3.08 hits per line

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

80.77
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
            if (this.outputListener != null) {
3✔
214
              for (OutputMessage msg : output) {
10✔
215
                this.outputListener.onOutput(msg.message(), msg.error());
7✔
216
              }
1✔
217
            }
218
          }
219

220
          if (Redirect.PIPE == processMode.getRedirectError()) {
4!
221
            errFut.get();
3✔
222
            if (this.outputListener != null) {
3✔
223
              for (OutputMessage msg : output) {
10✔
224
                this.outputListener.onOutput(msg.message(), msg.error());
7✔
225
              }
1✔
226
            }
227
          }
228
        }
229

230
        int exitCode;
231

232
        if (processMode.isBackground()) {
3✔
233
          exitCode = ProcessResult.SUCCESS;
3✔
234
        } else {
235
          exitCode = process.waitFor();
3✔
236
        }
237

238
        List<OutputMessage> finalOutput = new ArrayList<>(output);
5✔
239
        boolean success = this.exitCodeAcceptor.test(exitCode);
6✔
240
        ProcessResult result = new ProcessResultImpl(this.executable.getFileName().toString(), command, exitCode, success, finalOutput);
12✔
241

242
        performLogging(result, exitCode, interpreter);
5✔
243

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

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

274
    return CompletableFuture.supplyAsync(() -> {
6✔
275

276
      try (InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr)) {
10✔
277

278
        String line;
279
        while ((line = br.readLine()) != null) {
5✔
280
          OutputMessage outputMessage = new OutputMessage(errorStream, line);
6✔
281
          outputMessages.add(outputMessage);
4✔
282
        }
1✔
283

284
        return null;
4✔
285
      } catch (Throwable e) {
1✔
286
        throw new RuntimeException("There was a problem while executing the program", e);
6✔
287
      }
288
    });
289
  }
290

291
  private String createCommand() {
292
    String cmd = this.executable.toString();
4✔
293
    StringBuilder sb = new StringBuilder(cmd.length() + this.arguments.size() * 4);
12✔
294
    sb.append(cmd);
4✔
295
    for (String arg : this.arguments) {
11✔
296
      sb.append(' ');
4✔
297
      sb.append(arg);
4✔
298
    }
1✔
299
    return sb.toString();
3✔
300
  }
301

302
  private String createCommandMessage(String interpreter, String suffix) {
303

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

326
  private String getSheBang(Path file) {
327

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

356
  private String addExecutable(List<String> args) {
357

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

389
  private void performLogging(ProcessResult result, int exitCode, String interpreter) {
390

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

395
      LOG.atLevel(ideLogLevel.getSlf4jLevel()).log(message);
6✔
396
      result.log(ideLogLevel);
3✔
397

398
      if (this.errorHandling == ProcessErrorHandling.THROW_CLI) {
4!
399
        throw new CliProcessException(message, result);
×
400
      } else if (this.errorHandling == ProcessErrorHandling.THROW_ERR) {
4✔
401
        throw new IllegalStateException(message);
5✔
402
      }
403
    }
404
  }
1✔
405

406
  private void modifyArgumentsOnBackgroundProcess(ProcessMode processMode) {
407

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

410
    Path bash = this.context.findBash();
4✔
411
    if (bash == null) {
2!
412
      LOG.warn("Cannot start background process via bash because no bash installation was found. Hence, output will be discarded.");
×
413
      this.processBuilder.redirectOutput(Redirect.DISCARD).redirectError(Redirect.DISCARD);
×
414
      return;
×
415
    }
416

417
    String commandToRunInBackground = buildCommandToRunInBackground();
3✔
418

419
    this.arguments.clear();
3✔
420
    this.arguments.add(bash.toString());
6✔
421
    this.arguments.add("-c");
5✔
422
    commandToRunInBackground += " & disown";
3✔
423
    this.arguments.add(commandToRunInBackground);
5✔
424

425
  }
1✔
426

427
  private void applyRedirects(ProcessMode processMode) {
428

429
    Redirect output = processMode.getRedirectOutput();
3✔
430
    Redirect error = processMode.getRedirectError();
3✔
431
    Redirect input = processMode.getRedirectInput();
3✔
432

433
    if (output != null) {
2!
434
      this.processBuilder.redirectOutput(output);
5✔
435
    }
436
    if (error != null) {
2!
437
      this.processBuilder.redirectError(error);
5✔
438
    }
439
    if (input != null) {
2✔
440
      this.processBuilder.redirectInput(input);
5✔
441
    }
442
  }
1✔
443

444
  private String buildCommandToRunInBackground() {
445

446
    if (this.context.getSystemInfo().isWindows()) {
5!
447

448
      StringBuilder stringBuilder = new StringBuilder();
×
449

450
      for (String argument : this.arguments) {
×
451

452
        if (SystemInfoImpl.INSTANCE.isWindows() && SystemPath.isValidWindowsPath(argument)) {
×
453
          argument = WindowsPathSyntax.MSYS.normalize(argument);
×
454
        }
455

456
        stringBuilder.append(argument);
×
457
        stringBuilder.append(" ");
×
458
      }
×
459
      return stringBuilder.toString().trim();
×
460
    } else {
461
      return this.arguments.stream().map(Object::toString).collect(Collectors.joining(" "));
10✔
462
    }
463
  }
464
}
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