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

devonfw / IDEasy / 12674280211

08 Jan 2025 03:59PM UTC coverage: 67.541% (+0.06%) from 67.478%
12674280211

Pull #904

github

web-flow
Merge 387146b16 into 3a2451266
Pull Request #904: #881: add self healing feature to add x-flags before running command

2577 of 4158 branches covered (61.98%)

Branch coverage included in aggregate %.

6670 of 9533 relevant lines covered (69.97%)

3.08 hits per line

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

79.31
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(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

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

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

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

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

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

184
        int exitCode;
185

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

192
        ProcessResult result = new ProcessResultImpl(this.executable.getFileName().toString(), command, exitCode, out, err);
12✔
193

194
        performLogging(result, exitCode, interpreter);
5✔
195

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

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

225
    return CompletableFuture.supplyAsync(() -> {
4✔
226

227
      try (InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr)) {
10✔
228
        return br.lines().toList();
6✔
229
      } catch (Throwable e) {
1✔
230
        throw new RuntimeException("There was a problem while executing the program", e);
6✔
231
      }
232
    });
233
  }
234

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

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

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

270
  private String getSheBang(Path file) {
271

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

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

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

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

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

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

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

350
  private void modifyArgumentsOnBackgroundProcess(ProcessMode processMode) {
351

352
    if (processMode == ProcessMode.BACKGROUND) {
3✔
353
      this.processBuilder.redirectOutput(Redirect.INHERIT).redirectError(Redirect.INHERIT);
8✔
354
    } else if (processMode == ProcessMode.BACKGROUND_SILENT) {
3!
355
      this.processBuilder.redirectOutput(Redirect.DISCARD).redirectError(Redirect.DISCARD);
8✔
356
    } else {
357
      throw new IllegalStateException("Cannot handle non background process mode!");
×
358
    }
359

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

368
    String commandToRunInBackground = buildCommandToRunInBackground();
3✔
369

370
    this.arguments.clear();
3✔
371
    this.arguments.add(bash);
5✔
372
    this.arguments.add("-c");
5✔
373
    commandToRunInBackground += " & disown";
3✔
374
    this.arguments.add(commandToRunInBackground);
5✔
375

376
  }
1✔
377

378
  private String buildCommandToRunInBackground() {
379

380
    if (this.context.getSystemInfo().isWindows()) {
5!
381

382
      StringBuilder stringBuilder = new StringBuilder();
×
383

384
      for (String argument : this.arguments) {
×
385

386
        if (SystemInfoImpl.INSTANCE.isWindows() && SystemPath.isValidWindowsPath(argument)) {
×
387
          argument = WindowsPathSyntax.MSYS.normalize(argument);
×
388
        }
389

390
        stringBuilder.append(argument);
×
391
        stringBuilder.append(" ");
×
392
      }
×
393
      return stringBuilder.toString().trim();
×
394
    } else {
395
      return this.arguments.stream().map(Object::toString).collect(Collectors.joining(" "));
10✔
396
    }
397
  }
398
}
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