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

devonfw / IDEasy / 11611100303

31 Oct 2024 11:29AM UTC coverage: 66.915% (+0.2%) from 66.715%
11611100303

push

github

web-flow
#608: enhance error messages (#653)

2415 of 3952 branches covered (61.11%)

Branch coverage included in aggregate %.

6302 of 9075 relevant lines covered (69.44%)

3.06 hits per line

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

79.86
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.IdeLogLevel;
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

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

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

192
      performLogging(result, exitCode, interpreter);
5✔
193

194
      return result;
4✔
195

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

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

219
    return CompletableFuture.supplyAsync(() -> {
4✔
220

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

229
  private String createCommandMessage(String interpreter, String suffix) {
230

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

253
  private String getSheBang(Path file) {
254

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

283
  private String addExecutable(String exec, List<String> args) {
284

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

315
  private void performLogging(ProcessResult result, int exitCode, String interpreter) {
316

317
    if (!result.isSuccessful() && (this.errorHandling != ProcessErrorHandling.NONE)) {
7!
318
      IdeLogLevel ideLogLevel;
319
      String message = createCommandMessage(interpreter, "\nfailed with exit code " + exitCode + "!");
6✔
320

321
      if (this.errorHandling == ProcessErrorHandling.LOG_ERROR) {
4✔
322
        ideLogLevel = IdeLogLevel.ERROR;
3✔
323
      } else if (this.errorHandling == ProcessErrorHandling.LOG_WARNING) {
4✔
324
        ideLogLevel = IdeLogLevel.WARNING;
3✔
325
      } else {
326
        ideLogLevel = IdeLogLevel.ERROR;
2✔
327
        this.context.error("Internal error: Undefined error handling {}", this.errorHandling);
11✔
328
      }
329

330
      context.level(ideLogLevel).log(message);
6✔
331
      result.log(ideLogLevel, context);
5✔
332

333
      if (this.errorHandling == ProcessErrorHandling.THROW_CLI) {
4!
334
        throw new CliProcessException(message, result);
×
335
      } else if (this.errorHandling == ProcessErrorHandling.THROW_ERR) {
4✔
336
        throw new IllegalStateException(message);
5✔
337
      }
338
    }
339
  }
1✔
340

341
  private void modifyArgumentsOnBackgroundProcess(ProcessMode processMode) {
342

343
    if (processMode == ProcessMode.BACKGROUND) {
3✔
344
      this.processBuilder.redirectOutput(Redirect.INHERIT).redirectError(Redirect.INHERIT);
8✔
345
    } else if (processMode == ProcessMode.BACKGROUND_SILENT) {
3!
346
      this.processBuilder.redirectOutput(Redirect.DISCARD).redirectError(Redirect.DISCARD);
8✔
347
    } else {
348
      throw new IllegalStateException("Cannot handle non background process mode!");
×
349
    }
350

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

359
    String commandToRunInBackground = buildCommandToRunInBackground();
3✔
360

361
    this.arguments.clear();
3✔
362
    this.arguments.add(bash);
5✔
363
    this.arguments.add("-c");
5✔
364
    commandToRunInBackground += " & disown";
3✔
365
    this.arguments.add(commandToRunInBackground);
5✔
366

367
  }
1✔
368

369
  private String buildCommandToRunInBackground() {
370

371
    if (this.context.getSystemInfo().isWindows()) {
5!
372

373
      StringBuilder stringBuilder = new StringBuilder();
×
374

375
      for (String argument : this.arguments) {
×
376

377
        if (SystemInfoImpl.INSTANCE.isWindows() && SystemPath.isValidWindowsPath(argument)) {
×
378
          argument = WindowsPathSyntax.MSYS.normalize(argument);
×
379
        }
380

381
        stringBuilder.append(argument);
×
382
        stringBuilder.append(" ");
×
383
      }
×
384
      return stringBuilder.toString().trim();
×
385
    } else {
386
      return this.arguments.stream().map(Object::toString).collect(Collectors.joining(" "));
10✔
387
    }
388
  }
389
}
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

© 2025 Coveralls, Inc