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

devonfw / IDEasy / 17820842601

18 Sep 2025 07:05AM UTC coverage: 68.539% (-0.08%) from 68.618%
17820842601

push

github

web-flow
#1491: fix reuse software from repo (#1495)

3420 of 5461 branches covered (62.63%)

Branch coverage included in aggregate %.

8919 of 12542 relevant lines covered (71.11%)

3.12 hits per line

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

81.05
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 (this.executable == null) {
3✔
141
      throw new IllegalStateException("Missing executable to run process!");
5✔
142
    }
143

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

161
    try {
162
      applyRedirects(processMode);
3✔
163
      if (processMode.isBackground()) {
3✔
164
        modifyArgumentsOnBackgroundProcess(processMode);
3✔
165
      }
166

167
      this.processBuilder.command(args);
5✔
168

169
      ConcurrentLinkedQueue<OutputMessage> output = new ConcurrentLinkedQueue<>();
4✔
170

171
      Process process = this.processBuilder.start();
4✔
172

173
      try {
174
        if (processMode == ProcessMode.DEFAULT_CAPTURE) {
3✔
175
          CompletableFuture<Void> outFut = readInputStream(process.getInputStream(), false, output);
6✔
176
          CompletableFuture<Void> errFut = readInputStream(process.getErrorStream(), true, output);
6✔
177
          outFut.get();
3✔
178
          errFut.get();
3✔
179

180
          if (this.outputListener != null) {
3✔
181
            for (OutputMessage msg : output) {
10✔
182
              this.outputListener.onOutput(msg.message(), msg.error());
7✔
183
            }
1✔
184
          }
185
        }
186

187
        int exitCode;
188

189
        if (processMode.isBackground()) {
3✔
190
          exitCode = ProcessResult.SUCCESS;
3✔
191
        } else {
192
          exitCode = process.waitFor();
3✔
193
        }
194

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

198
        performLogging(result, exitCode, interpreter);
5✔
199

200
        return result;
4✔
201
      } finally {
202
        if (!processMode.isBackground()) {
3✔
203
          process.destroy();
2✔
204
        }
205
      }
206
    } catch (CliProcessException | IllegalStateException e) {
1✔
207
      // these exceptions are thrown from performLogOnError and we do not want to wrap them (see #593)
208
      throw e;
2✔
209
    } catch (Exception e) {
1✔
210
      String msg = e.getMessage();
3✔
211
      if ((msg == null) || msg.isEmpty()) {
5!
212
        msg = e.getClass().getSimpleName();
×
213
      }
214
      throw new IllegalStateException(createCommandMessage(interpreter, " failed: " + msg), e);
10✔
215
    } finally {
216
      this.arguments.clear();
3✔
217
    }
218
  }
219

220
  /**
221
   * Asynchronously and parallel reads {@link InputStream input stream} and stores it in {@link CompletableFuture}. Inspired by: <a href=
222
   * "https://stackoverflow.com/questions/14165517/processbuilder-forwarding-stdout-and-stderr-of-started-processes-without-blocki/57483714#57483714">StackOverflow</a>
223
   *
224
   * @param is {@link InputStream}.
225
   * @param errorStream to identify if the output came from stdout or stderr
226
   * @return {@link CompletableFuture}.
227
   */
228
  private static CompletableFuture<Void> readInputStream(InputStream is, boolean errorStream, ConcurrentLinkedQueue<OutputMessage> outputMessages) {
229

230
    return CompletableFuture.supplyAsync(() -> {
6✔
231

232
      try (InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr)) {
10✔
233

234
        String line;
235
        while ((line = br.readLine()) != null) {
5✔
236
          OutputMessage outputMessage = new OutputMessage(errorStream, line);
6✔
237
          outputMessages.add(outputMessage);
4✔
238
        }
1✔
239

240
        return null;
4✔
241
      } catch (Throwable e) {
1✔
242
        throw new RuntimeException("There was a problem while executing the program", e);
6✔
243
      }
244
    });
245
  }
246

247
  private String createCommand() {
248
    String cmd = this.executable.toString();
4✔
249
    StringBuilder sb = new StringBuilder(cmd.length() + this.arguments.size() * 4);
12✔
250
    sb.append(cmd);
4✔
251
    for (String arg : this.arguments) {
11✔
252
      sb.append(' ');
4✔
253
      sb.append(arg);
4✔
254
    }
1✔
255
    return sb.toString();
3✔
256
  }
257

258
  private String createCommandMessage(String interpreter, String suffix) {
259

260
    StringBuilder sb = new StringBuilder();
4✔
261
    sb.append("Running command '");
4✔
262
    sb.append(this.executable);
5✔
263
    sb.append("'");
4✔
264
    if (interpreter != null) {
2✔
265
      sb.append(" using ");
4✔
266
      sb.append(interpreter);
4✔
267
    }
268
    int size = this.arguments.size();
4✔
269
    if (size > 0) {
2✔
270
      sb.append(" with arguments");
4✔
271
      for (int i = 0; i < size; i++) {
7✔
272
        String arg = this.arguments.get(i);
6✔
273
        sb.append(" '");
4✔
274
        sb.append(arg);
4✔
275
        sb.append("'");
4✔
276
      }
277
    }
278
    sb.append(suffix);
4✔
279
    return sb.toString();
3✔
280
  }
281

282
  private String getSheBang(Path file) {
283

284
    try (InputStream in = Files.newInputStream(file)) {
5✔
285
      // "#!/usr/bin/env bash".length() = 19
286
      byte[] buffer = new byte[32];
3✔
287
      int read = in.read(buffer);
4✔
288
      if ((read > 2) && (buffer[0] == '#') && (buffer[1] == '!')) {
13!
289
        int start = 2;
2✔
290
        int end = 2;
2✔
291
        while (end < read) {
3!
292
          byte c = buffer[end];
4✔
293
          if ((c == '\n') || (c == '\r') || (c > 127)) {
9!
294
            break;
×
295
          } else if ((end == start) && (c == ' ')) {
6!
296
            start++;
×
297
          }
298
          end++;
1✔
299
        }
1✔
300
        String sheBang = new String(buffer, start, end - start, StandardCharsets.US_ASCII).trim();
11✔
301
        if (sheBang.startsWith(PREFIX_USR_BIN_ENV)) {
4!
302
          sheBang = sheBang.substring(PREFIX_USR_BIN_ENV.length());
×
303
        }
304
        return sheBang;
4✔
305
      }
306
    } catch (IOException e) {
5!
307
      // ignore...
308
    }
1✔
309
    return null;
2✔
310
  }
311

312
  private String addExecutable(List<String> args) {
313

314
    String interpreter = null;
2✔
315
    String fileExtension = FilenameUtil.getExtension(this.executable.getFileName().toString());
6✔
316
    boolean isBashScript = "sh".equals(fileExtension);
4✔
317
    this.context.getFileAccess().makeExecutable(this.executable, true);
7✔
318
    if (!isBashScript) {
2✔
319
      String sheBang = getSheBang(this.executable);
5✔
320
      if (sheBang != null) {
2✔
321
        String cmd = sheBang;
2✔
322
        int lastSlash = cmd.lastIndexOf('/');
4✔
323
        if (lastSlash >= 0) {
2!
324
          cmd = cmd.substring(lastSlash + 1);
6✔
325
        }
326
        if (cmd.equals("bash")) {
4!
327
          isBashScript = true;
2✔
328
        } else {
329
          // currently we do not support other interpreters...
330
        }
331
      }
332
    }
333
    if (isBashScript) {
2✔
334
      interpreter = "bash";
2✔
335
      args.add(this.context.findBashRequired());
6✔
336
    }
337
    if ("msi".equalsIgnoreCase(fileExtension)) {
4!
338
      args.add(0, "/i");
×
339
      args.add(0, "msiexec");
×
340
    }
341
    args.add(this.executable.toString());
6✔
342
    return interpreter;
2✔
343
  }
344

345
  private void performLogging(ProcessResult result, int exitCode, String interpreter) {
346

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

351
      context.level(ideLogLevel).log(message);
6✔
352
      result.log(ideLogLevel, context);
5✔
353

354
      if (this.errorHandling == ProcessErrorHandling.THROW_CLI) {
4!
355
        throw new CliProcessException(message, result);
×
356
      } else if (this.errorHandling == ProcessErrorHandling.THROW_ERR) {
4✔
357
        throw new IllegalStateException(message);
5✔
358
      }
359
    }
360
  }
1✔
361

362
  private void modifyArgumentsOnBackgroundProcess(ProcessMode processMode) {
363

364
    if (!processMode.isBackground()) {
3!
365
      throw new IllegalStateException("Cannot handle non background process mode!");
×
366
    }
367

368
    String bash = this.context.findBash();
4✔
369
    if (bash == null) {
2!
370
      this.context.warning(
×
371
          "Cannot start background process via bash because no bash installation was found. Hence, output will be discarded.");
372
      this.processBuilder.redirectOutput(Redirect.DISCARD).redirectError(Redirect.DISCARD);
×
373
      return;
×
374
    }
375

376
    String commandToRunInBackground = buildCommandToRunInBackground();
3✔
377

378
    this.arguments.clear();
3✔
379
    this.arguments.add(bash);
5✔
380
    this.arguments.add("-c");
5✔
381
    commandToRunInBackground += " & disown";
3✔
382
    this.arguments.add(commandToRunInBackground);
5✔
383

384
  }
1✔
385

386
  private void applyRedirects(ProcessMode processMode) {
387

388
    Redirect output = processMode.getRedirectOutput();
3✔
389
    Redirect error = processMode.getRedirectError();
3✔
390
    Redirect input = processMode.getRedirectInput();
3✔
391

392
    if (output != null) {
2!
393
      this.processBuilder.redirectOutput(output);
5✔
394
    }
395
    if (error != null) {
2!
396
      this.processBuilder.redirectError(error);
5✔
397
    }
398
    if (input != null) {
2✔
399
      this.processBuilder.redirectInput(input);
5✔
400
    }
401
  }
1✔
402

403
  private String buildCommandToRunInBackground() {
404

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

407
      StringBuilder stringBuilder = new StringBuilder();
×
408

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

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

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