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

devonfw / IDEasy / 11061200804

26 Sep 2024 10:27PM UTC coverage: 66.053% (-0.05%) from 66.107%
11061200804

push

github

web-flow
#593: #651: #564: #439: fixed bugs, refactored tool dependencies (#652)

2312 of 3848 branches covered (60.08%)

Branch coverage included in aggregate %.

6078 of 8854 relevant lines covered (68.65%)

3.03 hits per line

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

75.89
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.stream.Collectors;
17

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

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

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

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

38
  private final ProcessBuilder processBuilder;
39

40
  private final List<String> arguments;
41

42
  private Path executable;
43

44
  private String overriddenPath;
45

46
  private final List<Path> extraPathEntries;
47

48
  private ProcessErrorHandling errorHandling;
49

50
  /**
51
   * The constructor.
52
   *
53
   * @param context the owning {@link IdeContext}.
54
   */
55
  public ProcessContextImpl(IdeContext context) {
56

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

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

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

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

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

89
    return this;
×
90
  }
91

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

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

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

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

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

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

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

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

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

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

132
    if (processMode == ProcessMode.DEFAULT) {
3✔
133
      this.processBuilder.redirectOutput(Redirect.INHERIT).redirectError(Redirect.INHERIT);
7✔
134
    }
135

136
    if (processMode == ProcessMode.DEFAULT_SILENT) {
3!
137
      this.processBuilder.redirectOutput(Redirect.DISCARD).redirectError(Redirect.DISCARD);
×
138
    }
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(this.executable.toString(), args);
7✔
154
    args.addAll(this.arguments);
5✔
155
    if (this.context.debug().isEnabled()) {
5!
156
      String message = createCommandMessage(interpreter, " ...");
5✔
157
      this.context.debug(message);
4✔
158
    }
159

160
    try {
161

162
      if (processMode == ProcessMode.DEFAULT_CAPTURE) {
3✔
163
        this.processBuilder.redirectOutput(Redirect.PIPE).redirectError(Redirect.PIPE);
8✔
164
      } else if (processMode.isBackground()) {
3✔
165
        modifyArgumentsOnBackgroundProcess(processMode);
3✔
166
      }
167

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

170
      List<String> out = null;
2✔
171
      List<String> err = null;
2✔
172

173
      Process process = this.processBuilder.start();
4✔
174

175
      if (processMode == ProcessMode.DEFAULT_CAPTURE) {
3✔
176
        CompletableFuture<List<String>> outFut = readInputStream(process.getInputStream());
4✔
177
        CompletableFuture<List<String>> errFut = readInputStream(process.getErrorStream());
4✔
178
        out = outFut.get();
4✔
179
        err = errFut.get();
4✔
180
      }
181

182
      int exitCode;
183
      if (processMode.isBackground()) {
3✔
184
        exitCode = ProcessResult.SUCCESS;
3✔
185
      } else {
186
        exitCode = process.waitFor();
3✔
187
      }
188

189
      ProcessResult result = new ProcessResultImpl(exitCode, out, err);
7✔
190
      performLogOnError(result, exitCode, interpreter);
5✔
191

192
      return result;
4✔
193

194
    } catch (CliProcessException | IllegalStateException e) {
1✔
195
      // these exceptions are thrown from performLogOnError and we do not want to wrap them (see #593)
196
      throw e;
2✔
197
    } catch (Exception e) {
×
198
      String msg = e.getMessage();
×
199
      if ((msg == null) || msg.isEmpty()) {
×
200
        msg = e.getClass().getSimpleName();
×
201
      }
202
      throw new IllegalStateException(createCommandMessage(interpreter, " failed: " + msg), e);
×
203
    } finally {
204
      this.arguments.clear();
3✔
205
    }
206
  }
207

208
  /**
209
   * Asynchronously and parallel reads {@link InputStream input stream} and stores it in {@link CompletableFuture}. Inspired by: <a href=
210
   * "https://stackoverflow.com/questions/14165517/processbuilder-forwarding-stdout-and-stderr-of-started-processes-without-blocki/57483714#57483714">StackOverflow</a>
211
   *
212
   * @param is {@link InputStream}.
213
   * @return {@link CompletableFuture}.
214
   */
215
  private static CompletableFuture<List<String>> readInputStream(InputStream is) {
216

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

219
      try (InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr)) {
10✔
220
        return br.lines().toList();
6✔
221
      } catch (Throwable e) {
×
222
        throw new RuntimeException("There was a problem while executing the program", e);
×
223
      }
224
    });
225
  }
226

227
  private String createCommandMessage(String interpreter, String suffix) {
228

229
    StringBuilder sb = new StringBuilder();
4✔
230
    sb.append("Running command '");
4✔
231
    sb.append(this.executable);
5✔
232
    sb.append("'");
4✔
233
    if (interpreter != null) {
2✔
234
      sb.append(" using ");
4✔
235
      sb.append(interpreter);
4✔
236
    }
237
    int size = this.arguments.size();
4✔
238
    if (size > 0) {
2✔
239
      sb.append(" with arguments");
4✔
240
      for (int i = 0; i < size; i++) {
7✔
241
        String arg = this.arguments.get(i);
6✔
242
        sb.append(" '");
4✔
243
        sb.append(arg);
4✔
244
        sb.append("'");
4✔
245
      }
246
    }
247
    sb.append(suffix);
4✔
248
    return sb.toString();
3✔
249
  }
250

251
  private String getSheBang(Path file) {
252

253
    try (InputStream in = Files.newInputStream(file)) {
5✔
254
      // "#!/usr/bin/env bash".length() = 19
255
      byte[] buffer = new byte[32];
3✔
256
      int read = in.read(buffer);
4✔
257
      if ((read > 2) && (buffer[0] == '#') && (buffer[1] == '!')) {
13!
258
        int start = 2;
2✔
259
        int end = 2;
2✔
260
        while (end < read) {
3!
261
          byte c = buffer[end];
4✔
262
          if ((c == '\n') || (c == '\r') || (c > 127)) {
9!
263
            break;
×
264
          } else if ((end == start) && (c == ' ')) {
6!
265
            start++;
×
266
          }
267
          end++;
1✔
268
        }
1✔
269
        String sheBang = new String(buffer, start, end - start, StandardCharsets.US_ASCII).trim();
11✔
270
        if (sheBang.startsWith(PREFIX_USR_BIN_ENV)) {
4✔
271
          sheBang = sheBang.substring(PREFIX_USR_BIN_ENV.length());
5✔
272
        }
273
        return sheBang;
4✔
274
      }
275
    } catch (IOException e) {
5!
276
      // ignore...
277
    }
×
278
    return null;
2✔
279
  }
280

281
  private String addExecutable(String exec, List<String> args) {
282

283
    String interpreter = null;
2✔
284
    String fileExtension = FilenameUtil.getExtension(exec);
3✔
285
    boolean isBashScript = "sh".equals(fileExtension);
4✔
286
    if (!isBashScript) {
2✔
287
      String sheBang = getSheBang(this.executable);
5✔
288
      if (sheBang != null) {
2✔
289
        String cmd = sheBang;
2✔
290
        int lastSlash = cmd.lastIndexOf('/');
4✔
291
        if (lastSlash >= 0) {
2✔
292
          cmd = cmd.substring(lastSlash + 1);
6✔
293
        }
294
        if (cmd.equals("bash")) {
4!
295
          isBashScript = true;
2✔
296
        } else {
297
          // currently we do not support other interpreters...
298
        }
299
      }
300
    }
301
    if (isBashScript) {
2✔
302
      interpreter = "bash";
2✔
303
      args.add(this.context.findBashRequired());
6✔
304
    }
305
    if ("msi".equalsIgnoreCase(fileExtension)) {
4!
306
      args.add(0, "/i");
×
307
      args.add(0, "msiexec");
×
308
    }
309
    args.add(exec);
4✔
310
    return interpreter;
2✔
311
  }
312

313
  private void performLogOnError(ProcessResult result, int exitCode, String interpreter) {
314

315
    if (!result.isSuccessful() && (this.errorHandling != ProcessErrorHandling.NONE)) {
7!
316
      String message = createCommandMessage(interpreter, " failed with exit code " + exitCode + "!");
6✔
317
      if (this.errorHandling == ProcessErrorHandling.THROW_CLI) {
4!
318
        throw new CliProcessException(message, result);
×
319
      } else if (this.errorHandling == ProcessErrorHandling.THROW_ERR) {
4✔
320
        throw new IllegalStateException(message);
5✔
321
      }
322
      IdeSubLogger level;
323
      if (this.errorHandling == ProcessErrorHandling.LOG_ERROR) {
4✔
324
        level = this.context.error();
5✔
325
      } else if (this.errorHandling == ProcessErrorHandling.LOG_WARNING) {
4!
326
        level = this.context.warning();
5✔
327
      } else {
328
        level = this.context.error();
×
329
        this.context.error("Internal error: Undefined error handling {}", this.errorHandling);
×
330
      }
331
      level.log(message);
3✔
332
    }
333
  }
1✔
334

335
  private void modifyArgumentsOnBackgroundProcess(ProcessMode processMode) {
336

337
    if (processMode == ProcessMode.BACKGROUND) {
3✔
338
      this.processBuilder.redirectOutput(Redirect.INHERIT).redirectError(Redirect.INHERIT);
8✔
339
    } else if (processMode == ProcessMode.BACKGROUND_SILENT) {
3!
340
      this.processBuilder.redirectOutput(Redirect.DISCARD).redirectError(Redirect.DISCARD);
8✔
341
    } else {
342
      throw new IllegalStateException("Cannot handle non background process mode!");
×
343
    }
344

345
    String bash = this.context.findBash();
4✔
346
    if (bash == null) {
2!
347
      this.context.warning(
×
348
          "Cannot start background process via bash because no bash installation was found. Hence, output will be discarded.");
349
      this.processBuilder.redirectOutput(Redirect.DISCARD).redirectError(Redirect.DISCARD);
×
350
      return;
×
351
    }
352

353
    String commandToRunInBackground = buildCommandToRunInBackground();
3✔
354

355
    this.arguments.clear();
3✔
356
    this.arguments.add(bash);
5✔
357
    this.arguments.add("-c");
5✔
358
    commandToRunInBackground += " & disown";
3✔
359
    this.arguments.add(commandToRunInBackground);
5✔
360

361
  }
1✔
362

363
  private String buildCommandToRunInBackground() {
364

365
    if (this.context.getSystemInfo().isWindows()) {
5!
366

367
      StringBuilder stringBuilder = new StringBuilder();
×
368

369
      for (String argument : this.arguments) {
×
370

371
        if (SystemInfoImpl.INSTANCE.isWindows() && SystemPath.isValidWindowsPath(argument)) {
×
372
          argument = WindowsPathSyntax.MSYS.normalize(argument);
×
373
        }
374

375
        stringBuilder.append(argument);
×
376
        stringBuilder.append(" ");
×
377
      }
×
378
      return stringBuilder.toString().trim();
×
379
    } else {
380
      return this.arguments.stream().map(Object::toString).collect(Collectors.joining(" "));
10✔
381
    }
382
  }
383
}
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