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

devonfw / IDEasy / 15253665702

26 May 2025 12:14PM UTC coverage: 67.716% (-0.003%) from 67.719%
15253665702

push

github

web-flow
#1306 Redirect cleaned up in ProcessContext and ProcessMode (#1330)

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

3158 of 5066 branches covered (62.34%)

Branch coverage included in aggregate %.

8095 of 11552 relevant lines covered (70.07%)

3.07 hits per line

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

80.41
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
  /**
52
   * The constructor.
53
   *
54
   * @param context the owning {@link IdeContext}.
55
   */
56
  public ProcessContextImpl(IdeContext context) {
57

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

72
  @Override
73
  public ProcessContext errorHandling(ProcessErrorHandling handling) {
74

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

80
  @Override
81
  public ProcessContext directory(Path directory) {
82

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

90
    return this;
×
91
  }
92

93
  @Override
94
  public ProcessContext executable(Path command) {
95

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

100
    this.executable = command;
3✔
101
    return this;
2✔
102
  }
103

104
  @Override
105
  public ProcessContext addArg(String arg) {
106

107
    this.arguments.add(arg);
5✔
108
    return this;
2✔
109
  }
110

111
  @Override
112
  public ProcessContext withEnvVar(String key, String value) {
113

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

123
  @Override
124
  public ProcessContext withPathEntry(Path path) {
125

126
    this.extraPathEntries.add(path);
5✔
127
    return this;
2✔
128
  }
129

130
  @Override
131
  public ProcessResult run(ProcessMode processMode) {
132

133
    if (this.executable == null) {
3✔
134
      throw new IllegalStateException("Missing executable to run process!");
5✔
135
    }
136

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

154
    try {
155
      applyRedirects(processMode);
3✔
156
      if (processMode.isBackground()) {
3✔
157
        modifyArgumentsOnBackgroundProcess(processMode);
3✔
158
      }
159

160
      this.processBuilder.command(args);
5✔
161

162
      ConcurrentLinkedQueue<OutputMessage> output = new ConcurrentLinkedQueue<>();
4✔
163

164
      Process process = this.processBuilder.start();
4✔
165

166
      try {
167
        if (processMode == ProcessMode.DEFAULT_CAPTURE) {
3✔
168
          CompletableFuture<Void> outFut = readInputStream(process.getInputStream(), false, output);
6✔
169
          CompletableFuture<Void> errFut = readInputStream(process.getErrorStream(), true, output);
6✔
170
          outFut.get();
3✔
171
          errFut.get();
3✔
172
        }
173

174
        int exitCode;
175

176
        if (processMode.isBackground()) {
3✔
177
          exitCode = ProcessResult.SUCCESS;
3✔
178
        } else {
179
          exitCode = process.waitFor();
3✔
180
        }
181

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

185
        performLogging(result, exitCode, interpreter);
5✔
186

187
        return result;
4✔
188
      } finally {
189
        if (!processMode.isBackground()) {
3✔
190
          process.destroy();
2✔
191
        }
192
      }
193
    } catch (CliProcessException | IllegalStateException e) {
1✔
194
      // these exceptions are thrown from performLogOnError and we do not want to wrap them (see #593)
195
      throw e;
2✔
196
    } catch (Exception e) {
1✔
197
      String msg = e.getMessage();
3✔
198
      if ((msg == null) || msg.isEmpty()) {
5!
199
        msg = e.getClass().getSimpleName();
×
200
      }
201
      throw new IllegalStateException(createCommandMessage(interpreter, " failed: " + msg), e);
10✔
202
    } finally {
203
      this.arguments.clear();
3✔
204
    }
205
  }
206

207
  /**
208
   * Asynchronously and parallel reads {@link InputStream input stream} and stores it in {@link CompletableFuture}. Inspired by: <a href=
209
   * "https://stackoverflow.com/questions/14165517/processbuilder-forwarding-stdout-and-stderr-of-started-processes-without-blocki/57483714#57483714">StackOverflow</a>
210
   *
211
   * @param is {@link InputStream}.
212
   * @param errorStream to identify if the output came from stdout or stderr
213
   * @return {@link CompletableFuture}.
214
   */
215
  private static CompletableFuture<Void> readInputStream(InputStream is, boolean errorStream, ConcurrentLinkedQueue<OutputMessage> outputMessages) {
216

217
    return CompletableFuture.supplyAsync(() -> {
6✔
218

219
      try (InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr)) {
10✔
220

221
        String line;
222
        while ((line = br.readLine()) != null) {
5✔
223
          OutputMessage outputMessage = new OutputMessage(errorStream, line);
6✔
224
          outputMessages.add(outputMessage);
4✔
225
        }
1✔
226

227
        return null;
4✔
228
      } catch (Throwable e) {
1✔
229
        throw new RuntimeException("There was a problem while executing the program", e);
6✔
230
      }
231
    });
232
  }
233

234
  private String createCommand() {
235
    String cmd = this.executable.toString();
4✔
236
    StringBuilder sb = new StringBuilder(cmd.length() + this.arguments.size() * 4);
12✔
237
    sb.append(cmd);
4✔
238
    for (String arg : this.arguments) {
11✔
239
      sb.append(' ');
4✔
240
      sb.append(arg);
4✔
241
    }
1✔
242
    return sb.toString();
3✔
243
  }
244

245
  private String createCommandMessage(String interpreter, String suffix) {
246

247
    StringBuilder sb = new StringBuilder();
4✔
248
    sb.append("Running command '");
4✔
249
    sb.append(this.executable);
5✔
250
    sb.append("'");
4✔
251
    if (interpreter != null) {
2✔
252
      sb.append(" using ");
4✔
253
      sb.append(interpreter);
4✔
254
    }
255
    int size = this.arguments.size();
4✔
256
    if (size > 0) {
2✔
257
      sb.append(" with arguments");
4✔
258
      for (int i = 0; i < size; i++) {
7✔
259
        String arg = this.arguments.get(i);
6✔
260
        sb.append(" '");
4✔
261
        sb.append(arg);
4✔
262
        sb.append("'");
4✔
263
      }
264
    }
265
    sb.append(suffix);
4✔
266
    return sb.toString();
3✔
267
  }
268

269
  private String getSheBang(Path file) {
270

271
    try (InputStream in = Files.newInputStream(file)) {
5✔
272
      // "#!/usr/bin/env bash".length() = 19
273
      byte[] buffer = new byte[32];
3✔
274
      int read = in.read(buffer);
4✔
275
      if ((read > 2) && (buffer[0] == '#') && (buffer[1] == '!')) {
13!
276
        int start = 2;
2✔
277
        int end = 2;
2✔
278
        while (end < read) {
3!
279
          byte c = buffer[end];
4✔
280
          if ((c == '\n') || (c == '\r') || (c > 127)) {
9!
281
            break;
×
282
          } else if ((end == start) && (c == ' ')) {
6!
283
            start++;
×
284
          }
285
          end++;
1✔
286
        }
1✔
287
        String sheBang = new String(buffer, start, end - start, StandardCharsets.US_ASCII).trim();
11✔
288
        if (sheBang.startsWith(PREFIX_USR_BIN_ENV)) {
4!
289
          sheBang = sheBang.substring(PREFIX_USR_BIN_ENV.length());
×
290
        }
291
        return sheBang;
4✔
292
      }
293
    } catch (IOException e) {
5!
294
      // ignore...
295
    }
1✔
296
    return null;
2✔
297
  }
298

299
  private String addExecutable(List<String> args) {
300

301
    String interpreter = null;
2✔
302
    String fileExtension = FilenameUtil.getExtension(this.executable.getFileName().toString());
6✔
303
    boolean isBashScript = "sh".equals(fileExtension);
4✔
304
    this.context.getFileAccess().makeExecutable(this.executable, true);
7✔
305
    if (!isBashScript) {
2✔
306
      String sheBang = getSheBang(this.executable);
5✔
307
      if (sheBang != null) {
2✔
308
        String cmd = sheBang;
2✔
309
        int lastSlash = cmd.lastIndexOf('/');
4✔
310
        if (lastSlash >= 0) {
2!
311
          cmd = cmd.substring(lastSlash + 1);
6✔
312
        }
313
        if (cmd.equals("bash")) {
4!
314
          isBashScript = true;
2✔
315
        } else {
316
          // currently we do not support other interpreters...
317
        }
318
      }
319
    }
320
    if (isBashScript) {
2✔
321
      interpreter = "bash";
2✔
322
      args.add(this.context.findBashRequired());
6✔
323
    }
324
    if ("msi".equalsIgnoreCase(fileExtension)) {
4!
325
      args.add(0, "/i");
×
326
      args.add(0, "msiexec");
×
327
    }
328
    args.add(this.executable.toString());
6✔
329
    return interpreter;
2✔
330
  }
331

332
  private void performLogging(ProcessResult result, int exitCode, String interpreter) {
333

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

338
      context.level(ideLogLevel).log(message);
6✔
339
      result.log(ideLogLevel, context);
5✔
340

341
      if (this.errorHandling == ProcessErrorHandling.THROW_CLI) {
4!
342
        throw new CliProcessException(message, result);
×
343
      } else if (this.errorHandling == ProcessErrorHandling.THROW_ERR) {
4✔
344
        throw new IllegalStateException(message);
5✔
345
      }
346
    }
347
  }
1✔
348

349
  private void modifyArgumentsOnBackgroundProcess(ProcessMode processMode) {
350

351
    if (!processMode.isBackground()) {
3!
352
      throw new IllegalStateException("Cannot handle non background process mode!");
×
353
    }
354

355
    String bash = this.context.findBash();
4✔
356
    if (bash == null) {
2!
357
      this.context.warning(
×
358
          "Cannot start background process via bash because no bash installation was found. Hence, output will be discarded.");
359
      this.processBuilder.redirectOutput(Redirect.DISCARD).redirectError(Redirect.DISCARD);
×
360
      return;
×
361
    }
362

363
    String commandToRunInBackground = buildCommandToRunInBackground();
3✔
364

365
    this.arguments.clear();
3✔
366
    this.arguments.add(bash);
5✔
367
    this.arguments.add("-c");
5✔
368
    commandToRunInBackground += " & disown";
3✔
369
    this.arguments.add(commandToRunInBackground);
5✔
370

371
  }
1✔
372

373
  private void applyRedirects(ProcessMode processMode) {
374

375
    Redirect output = processMode.getRedirectOutput();
3✔
376
    Redirect error = processMode.getRedirectError();
3✔
377
    Redirect input = processMode.getRedirectInput();
3✔
378

379
    if (output != null) {
2!
380
      this.processBuilder.redirectOutput(output);
5✔
381
    }
382
    if (error != null) {
2!
383
      this.processBuilder.redirectError(error);
5✔
384
    }
385
    if (input != null) {
2✔
386
      this.processBuilder.redirectInput(input);
5✔
387
    }
388
  }
1✔
389

390
  private String buildCommandToRunInBackground() {
391

392
    if (this.context.getSystemInfo().isWindows()) {
5!
393

394
      StringBuilder stringBuilder = new StringBuilder();
×
395

396
      for (String argument : this.arguments) {
×
397

398
        if (SystemInfoImpl.INSTANCE.isWindows() && SystemPath.isValidWindowsPath(argument)) {
×
399
          argument = WindowsPathSyntax.MSYS.normalize(argument);
×
400
        }
401

402
        stringBuilder.append(argument);
×
403
        stringBuilder.append(" ");
×
404
      }
×
405
      return stringBuilder.toString().trim();
×
406
    } else {
407
      return this.arguments.stream().map(Object::toString).collect(Collectors.joining(" "));
10✔
408
    }
409
  }
410
}
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