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

devonfw / IDEasy / 12073943517

28 Nov 2024 06:24PM UTC coverage: 67.417% (+0.03%) from 67.39%
12073943517

push

github

web-flow
#778: add icd #779: use functions instead of alias #810: setup in current shell #782: fix IDE_ROOT on linux/mac #774: fixed HTTP proxy support (#811)

2500 of 4050 branches covered (61.73%)

Branch coverage included in aggregate %.

6511 of 9316 relevant lines covered (69.89%)

3.09 hits per line

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

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

183
        int exitCode;
184

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

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

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

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

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

222
    return CompletableFuture.supplyAsync(() -> {
4✔
223

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

232
  private String createCommandMessage(String interpreter, String suffix) {
233

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

256
  private String getSheBang(Path file) {
257

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

286
  private String addExecutable(String exec, List<String> args) {
287

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

318
  private void performLogging(ProcessResult result, int exitCode, String interpreter) {
319

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

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

333
      context.level(ideLogLevel).log(message);
6✔
334
      result.log(ideLogLevel, context);
5✔
335

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

344
  private void modifyArgumentsOnBackgroundProcess(ProcessMode processMode) {
345

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

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

362
    String commandToRunInBackground = buildCommandToRunInBackground();
3✔
363

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

370
  }
1✔
371

372
  private String buildCommandToRunInBackground() {
373

374
    if (this.context.getSystemInfo().isWindows()) {
5!
375

376
      StringBuilder stringBuilder = new StringBuilder();
×
377

378
      for (String argument : this.arguments) {
×
379

380
        if (SystemInfoImpl.INSTANCE.isWindows() && SystemPath.isValidWindowsPath(argument)) {
×
381
          argument = WindowsPathSyntax.MSYS.normalize(argument);
×
382
        }
383

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