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

devonfw / IDEasy / 15068368140

16 May 2025 12:24PM UTC coverage: 67.728% (+0.02%) from 67.707%
15068368140

Pull #1308

github

web-flow
Merge cfc86a45d into 5e3c8fc69
Pull Request #1308: #716 Add VSCode extension installation visualization

3109 of 4998 branches covered (62.2%)

Branch coverage included in aggregate %.

7995 of 11397 relevant lines covered (70.15%)

3.07 hits per line

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

81.11
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.stream.Collectors;
18

19
import com.devonfw.tools.ide.cli.CliProcessException;
20
import com.devonfw.tools.ide.common.SystemPath;
21
import com.devonfw.tools.ide.context.IdeContext;
22
import com.devonfw.tools.ide.environment.VariableLine;
23
import com.devonfw.tools.ide.log.IdeLogLevel;
24
import com.devonfw.tools.ide.os.SystemInfoImpl;
25
import com.devonfw.tools.ide.os.WindowsPathSyntax;
26
import com.devonfw.tools.ide.util.FilenameUtil;
27
import com.devonfw.tools.ide.variable.IdeVariables;
28

29
/**
30
 * Implementation of {@link ProcessContext}.
31
 */
32
public class ProcessContextImpl implements ProcessContext {
33

34
  private static final String PREFIX_USR_BIN_ENV = "/usr/bin/env ";
35

36
  /** The owning {@link IdeContext}. */
37
  protected final IdeContext context;
38

39
  private final ProcessBuilder processBuilder;
40

41
  private final List<String> arguments;
42

43
  private Path executable;
44

45
  private String overriddenPath;
46

47
  private final List<Path> extraPathEntries;
48

49
  private ProcessErrorHandling errorHandling;
50

51
  private OutputListener outputListener;
52

53
  /**
54
   * The constructor.
55
   *
56
   * @param context the owning {@link IdeContext}.
57
   */
58
  public ProcessContextImpl(IdeContext context) {
59

60
    super();
2✔
61
    this.context = context;
3✔
62
    this.processBuilder = new ProcessBuilder();
7✔
63
    this.errorHandling = ProcessErrorHandling.THROW_ERR;
3✔
64
    Map<String, String> environment = this.processBuilder.environment();
4✔
65
    for (VariableLine var : this.context.getVariables().collectExportedVariables()) {
13✔
66
      if (var.isExport()) {
3!
67
        environment.put(var.getName(), var.getValue());
7✔
68
      }
69
    }
1✔
70
    this.arguments = new ArrayList<>();
5✔
71
    this.extraPathEntries = new ArrayList<>();
5✔
72
  }
1✔
73

74
  @Override
75
  public ProcessContext errorHandling(ProcessErrorHandling handling) {
76

77
    Objects.requireNonNull(handling);
3✔
78
    this.errorHandling = handling;
3✔
79
    return this;
2✔
80
  }
81

82
  @Override
83
  public ProcessContext directory(Path directory) {
84

85
    if (directory != null) {
×
86
      this.processBuilder.directory(directory.toFile());
×
87
    } else {
88
      this.context.debug(
×
89
          "Could not set the process builder's working directory! Directory of the current java process is used.");
90
    }
91

92
    return this;
×
93
  }
94

95
  @Override
96
  public ProcessContext executable(Path command) {
97

98
    if (!this.arguments.isEmpty()) {
4!
99
      throw new IllegalStateException("Arguments already present - did you forget to call run for previous call?");
×
100
    }
101

102
    this.executable = command;
3✔
103
    return this;
2✔
104
  }
105

106
  @Override
107
  public ProcessContext addArg(String arg) {
108

109
    this.arguments.add(arg);
5✔
110
    return this;
2✔
111
  }
112

113
  @Override
114
  public ProcessContext withEnvVar(String key, String value) {
115

116
    if (IdeVariables.PATH.getName().equals(key)) {
5!
117
      this.overriddenPath = value;
×
118
    } else {
119
      this.context.trace("Setting process environment variable {}={}", key, value);
14✔
120
      this.processBuilder.environment().put(key, value);
7✔
121
    }
122
    return this;
2✔
123
  }
124

125
  @Override
126
  public ProcessContext withPathEntry(Path path) {
127

128
    this.extraPathEntries.add(path);
5✔
129
    return this;
2✔
130
  }
131

132
  @Override
133
  public void setOutputListener(OutputListener listener) {
134
    this.outputListener = listener;
3✔
135
  }
1✔
136

137
  @Override
138
  public ProcessResult run(ProcessMode processMode) {
139

140
    if (processMode == ProcessMode.DEFAULT) {
3✔
141
      this.processBuilder.redirectOutput(Redirect.INHERIT).redirectError(Redirect.INHERIT);
7✔
142
    }
143

144
    if (processMode == ProcessMode.DEFAULT_SILENT) {
3!
145
      this.processBuilder.redirectOutput(Redirect.DISCARD).redirectError(Redirect.DISCARD);
×
146
    }
147

148
    if (this.executable == null) {
3✔
149
      throw new IllegalStateException("Missing executable to run process!");
5✔
150
    }
151

152
    SystemPath systemPath = this.context.getPath();
4✔
153
    if ((this.overriddenPath != null) || !this.extraPathEntries.isEmpty()) {
7!
154
      systemPath = systemPath.withPath(this.overriddenPath, this.extraPathEntries);
7✔
155
    }
156
    String path = systemPath.toString();
3✔
157
    this.context.trace("Setting PATH for process execution of {} to {}", this.executable.getFileName(), path);
16✔
158
    this.executable = systemPath.findBinary(this.executable);
6✔
159
    this.processBuilder.environment().put(IdeVariables.PATH.getName(), path);
8✔
160
    List<String> args = new ArrayList<>(this.arguments.size() + 4);
9✔
161
    String interpreter = addExecutable(args);
4✔
162
    args.addAll(this.arguments);
5✔
163
    String command = createCommand();
3✔
164
    if (this.context.debug().isEnabled()) {
5!
165
      String message = createCommandMessage(interpreter, " ...");
5✔
166
      this.context.debug(message);
4✔
167
    }
168

169
    try {
170

171
      if (processMode == ProcessMode.DEFAULT_CAPTURE) {
3✔
172
        this.processBuilder.redirectOutput(Redirect.PIPE).redirectError(Redirect.PIPE);
8✔
173
      } else if (processMode.isBackground()) {
3✔
174
        modifyArgumentsOnBackgroundProcess(processMode);
4✔
175
      } else {
176
        this.processBuilder.redirectInput(Redirect.INHERIT);
5✔
177
      }
178

179
      this.processBuilder.command(args);
5✔
180

181
      ConcurrentLinkedQueue<OutputMessage> output = new ConcurrentLinkedQueue<>();
4✔
182

183
      Process process = this.processBuilder.start();
4✔
184

185
      try {
186
        if (processMode == ProcessMode.DEFAULT_CAPTURE) {
3✔
187
          CompletableFuture<Void> outFut = readInputStream(process.getInputStream(), false, output);
6✔
188
          CompletableFuture<Void> errFut = readInputStream(process.getErrorStream(), true, output);
6✔
189
          outFut.get();
3✔
190
          errFut.get();
3✔
191

192
          if (this.outputListener != null) {
3✔
193
            for (OutputMessage msg : output) {
10✔
194
              this.outputListener.onOutput(msg.message(), msg.error());
7✔
195
            }
1✔
196
          }
197
        }
198

199
        int exitCode;
200

201
        if (processMode.isBackground()) {
3✔
202
          exitCode = ProcessResult.SUCCESS;
3✔
203
        } else {
204
          exitCode = process.waitFor();
3✔
205
        }
206

207
        List<OutputMessage> finalOutput = new ArrayList<>(output);
5✔
208
        ProcessResult result = new ProcessResultImpl(this.executable.getFileName().toString(), command, exitCode, finalOutput);
11✔
209

210
        performLogging(result, exitCode, interpreter);
5✔
211

212
        return result;
4✔
213
      } finally {
214
        if (!processMode.isBackground()) {
3✔
215
          process.destroy();
2✔
216
        }
217
      }
218
    } catch (CliProcessException | IllegalStateException e) {
1✔
219
      // these exceptions are thrown from performLogOnError and we do not want to wrap them (see #593)
220
      throw e;
2✔
221
    } catch (Exception e) {
1✔
222
      String msg = e.getMessage();
3✔
223
      if ((msg == null) || msg.isEmpty()) {
5!
224
        msg = e.getClass().getSimpleName();
×
225
      }
226
      throw new IllegalStateException(createCommandMessage(interpreter, " failed: " + msg), e);
10✔
227
    } finally {
228
      this.arguments.clear();
3✔
229
    }
230
  }
231

232
  /**
233
   * Asynchronously and parallel reads {@link InputStream input stream} and stores it in {@link CompletableFuture}. Inspired by: <a href=
234
   * "https://stackoverflow.com/questions/14165517/processbuilder-forwarding-stdout-and-stderr-of-started-processes-without-blocki/57483714#57483714">StackOverflow</a>
235
   *
236
   * @param is {@link InputStream}.
237
   * @param errorStream to identify if the output came from stdout or stderr
238
   * @return {@link CompletableFuture}.
239
   */
240
  private static CompletableFuture<Void> readInputStream(InputStream is, boolean errorStream, ConcurrentLinkedQueue<OutputMessage> outputMessages) {
241

242
    return CompletableFuture.supplyAsync(() -> {
6✔
243

244
      try (InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr)) {
10✔
245

246
        String line;
247
        while ((line = br.readLine()) != null) {
5✔
248
          OutputMessage outputMessage = new OutputMessage(errorStream, line);
6✔
249
          outputMessages.add(outputMessage);
4✔
250
        }
1✔
251

252
        return null;
4✔
253
      } catch (Throwable e) {
1✔
254
        throw new RuntimeException("There was a problem while executing the program", e);
6✔
255
      }
256
    });
257
  }
258

259
  private String createCommand() {
260
    String cmd = this.executable.toString();
4✔
261
    StringBuilder sb = new StringBuilder(cmd.length() + this.arguments.size() * 4);
12✔
262
    sb.append(cmd);
4✔
263
    for (String arg : this.arguments) {
11✔
264
      sb.append(' ');
4✔
265
      sb.append(arg);
4✔
266
    }
1✔
267
    return sb.toString();
3✔
268
  }
269

270
  private String createCommandMessage(String interpreter, String suffix) {
271

272
    StringBuilder sb = new StringBuilder();
4✔
273
    sb.append("Running command '");
4✔
274
    sb.append(this.executable);
5✔
275
    sb.append("'");
4✔
276
    if (interpreter != null) {
2✔
277
      sb.append(" using ");
4✔
278
      sb.append(interpreter);
4✔
279
    }
280
    int size = this.arguments.size();
4✔
281
    if (size > 0) {
2✔
282
      sb.append(" with arguments");
4✔
283
      for (int i = 0; i < size; i++) {
7✔
284
        String arg = this.arguments.get(i);
6✔
285
        sb.append(" '");
4✔
286
        sb.append(arg);
4✔
287
        sb.append("'");
4✔
288
      }
289
    }
290
    sb.append(suffix);
4✔
291
    return sb.toString();
3✔
292
  }
293

294
  private String getSheBang(Path file) {
295

296
    try (InputStream in = Files.newInputStream(file)) {
5✔
297
      // "#!/usr/bin/env bash".length() = 19
298
      byte[] buffer = new byte[32];
3✔
299
      int read = in.read(buffer);
4✔
300
      if ((read > 2) && (buffer[0] == '#') && (buffer[1] == '!')) {
13!
301
        int start = 2;
2✔
302
        int end = 2;
2✔
303
        while (end < read) {
3!
304
          byte c = buffer[end];
4✔
305
          if ((c == '\n') || (c == '\r') || (c > 127)) {
9!
306
            break;
×
307
          } else if ((end == start) && (c == ' ')) {
6!
308
            start++;
×
309
          }
310
          end++;
1✔
311
        }
1✔
312
        String sheBang = new String(buffer, start, end - start, StandardCharsets.US_ASCII).trim();
11✔
313
        if (sheBang.startsWith(PREFIX_USR_BIN_ENV)) {
4!
314
          sheBang = sheBang.substring(PREFIX_USR_BIN_ENV.length());
×
315
        }
316
        return sheBang;
4✔
317
      }
318
    } catch (IOException e) {
5!
319
      // ignore...
320
    }
1✔
321
    return null;
2✔
322
  }
323

324
  private String addExecutable(List<String> args) {
325

326
    String interpreter = null;
2✔
327
    String fileExtension = FilenameUtil.getExtension(this.executable.getFileName().toString());
6✔
328
    boolean isBashScript = "sh".equals(fileExtension);
4✔
329
    this.context.getFileAccess().makeExecutable(this.executable, true);
7✔
330
    if (!isBashScript) {
2✔
331
      String sheBang = getSheBang(this.executable);
5✔
332
      if (sheBang != null) {
2✔
333
        String cmd = sheBang;
2✔
334
        int lastSlash = cmd.lastIndexOf('/');
4✔
335
        if (lastSlash >= 0) {
2!
336
          cmd = cmd.substring(lastSlash + 1);
6✔
337
        }
338
        if (cmd.equals("bash")) {
4!
339
          isBashScript = true;
2✔
340
        } else {
341
          // currently we do not support other interpreters...
342
        }
343
      }
344
    }
345
    if (isBashScript) {
2✔
346
      interpreter = "bash";
2✔
347
      args.add(this.context.findBashRequired());
6✔
348
    }
349
    if ("msi".equalsIgnoreCase(fileExtension)) {
4!
350
      args.add(0, "/i");
×
351
      args.add(0, "msiexec");
×
352
    }
353
    args.add(this.executable.toString());
6✔
354
    return interpreter;
2✔
355
  }
356

357
  private void performLogging(ProcessResult result, int exitCode, String interpreter) {
358

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

363
      context.level(ideLogLevel).log(message);
6✔
364
      result.log(ideLogLevel, context);
5✔
365

366
      if (this.errorHandling == ProcessErrorHandling.THROW_CLI) {
4!
367
        throw new CliProcessException(message, result);
×
368
      } else if (this.errorHandling == ProcessErrorHandling.THROW_ERR) {
4✔
369
        throw new IllegalStateException(message);
5✔
370
      }
371
    }
372
  }
1✔
373

374
  private void modifyArgumentsOnBackgroundProcess(ProcessMode processMode) {
375

376
    if (processMode == ProcessMode.BACKGROUND) {
3✔
377
      this.processBuilder.redirectOutput(Redirect.INHERIT).redirectError(Redirect.INHERIT);
8✔
378
    } else if (processMode == ProcessMode.BACKGROUND_SILENT) {
3!
379
      this.processBuilder.redirectOutput(Redirect.DISCARD).redirectError(Redirect.DISCARD);
8✔
380
    } else {
381
      throw new IllegalStateException("Cannot handle non background process mode!");
×
382
    }
383

384
    String bash = this.context.findBash();
4✔
385
    if (bash == null) {
2!
386
      this.context.warning(
×
387
          "Cannot start background process via bash because no bash installation was found. Hence, output will be discarded.");
388
      this.processBuilder.redirectOutput(Redirect.DISCARD).redirectError(Redirect.DISCARD);
×
389
      return;
×
390
    }
391

392
    String commandToRunInBackground = buildCommandToRunInBackground();
3✔
393

394
    this.arguments.clear();
3✔
395
    this.arguments.add(bash);
5✔
396
    this.arguments.add("-c");
5✔
397
    commandToRunInBackground += " & disown";
3✔
398
    this.arguments.add(commandToRunInBackground);
5✔
399

400
  }
1✔
401

402
  private String buildCommandToRunInBackground() {
403

404
    if (this.context.getSystemInfo().isWindows()) {
5!
405

406
      StringBuilder stringBuilder = new StringBuilder();
×
407

408
      for (String argument : this.arguments) {
×
409

410
        if (SystemInfoImpl.INSTANCE.isWindows() && SystemPath.isValidWindowsPath(argument)) {
×
411
          argument = WindowsPathSyntax.MSYS.normalize(argument);
×
412
        }
413

414
        stringBuilder.append(argument);
×
415
        stringBuilder.append(" ");
×
416
      }
×
417
      return stringBuilder.toString().trim();
×
418
    } else {
419
      return this.arguments.stream().map(Object::toString).collect(Collectors.joining(" "));
10✔
420
    }
421
  }
422
}
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