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

devonfw / IDEasy / 13327588889

14 Feb 2025 10:44AM UTC coverage: 67.947% (-0.5%) from 68.469%
13327588889

Pull #1021

github

web-flow
Merge d03159bfe into 52609dacb
Pull Request #1021: #786: support ide upgrade to automatically update to the latest version of IDEasy

2964 of 4791 branches covered (61.87%)

Branch coverage included in aggregate %.

7688 of 10886 relevant lines covered (70.62%)

3.07 hits per line

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

78.39
cli/src/main/java/com/devonfw/tools/ide/environment/AbstractEnvironmentVariables.java
1
package com.devonfw.tools.ide.environment;
2

3
import java.nio.file.Path;
4
import java.util.ArrayList;
5
import java.util.HashMap;
6
import java.util.List;
7
import java.util.Map;
8
import java.util.regex.Matcher;
9

10
import com.devonfw.tools.ide.context.IdeContext;
11
import com.devonfw.tools.ide.log.IdeLogLevel;
12
import com.devonfw.tools.ide.variable.IdeVariables;
13
import com.devonfw.tools.ide.variable.VariableDefinition;
14
import com.devonfw.tools.ide.variable.VariableSyntax;
15
import com.devonfw.tools.ide.version.VersionIdentifier;
16

17
/**
18
 * Abstract base implementation of {@link EnvironmentVariables}.
19
 */
20
public abstract class AbstractEnvironmentVariables implements EnvironmentVariables {
21

22
  /**
23
   * When we replace variable expressions with their value the resulting {@link String} can change in size (shrink or grow). By adding a bit of extra capacity
24
   * we reduce the chance that the capacity is too small and a new buffer array has to be allocated and array-copy has to be performed.
25
   */
26
  private static final int EXTRA_CAPACITY = 8;
27

28
  private static final String SELF_REFERENCING_NOT_FOUND = "";
29

30
  private static final int MAX_RECURSION = 9;
31

32
  /**
33
   * @see #getParent()
34
   */
35
  protected final AbstractEnvironmentVariables parent;
36

37
  /**
38
   * The {@link IdeContext} instance.
39
   */
40
  protected final IdeContext context;
41

42
  private VariableSource source;
43

44
  /**
45
   * The constructor.
46
   *
47
   * @param parent the parent {@link EnvironmentVariables} to inherit from.
48
   * @param context the {@link IdeContext}.
49
   */
50
  public AbstractEnvironmentVariables(AbstractEnvironmentVariables parent, IdeContext context) {
51

52
    super();
2✔
53
    this.parent = parent;
3✔
54
    if (context == null) {
2!
55
      if (parent == null) {
×
56
        throw new IllegalArgumentException("parent and logger must not both be null!");
×
57
      }
58
      this.context = parent.context;
×
59
    } else {
60
      this.context = context;
3✔
61
    }
62
  }
1✔
63

64
  @Override
65
  public EnvironmentVariables getParent() {
66

67
    return this.parent;
3✔
68
  }
69

70
  @Override
71
  public Path getPropertiesFilePath() {
72

73
    return null;
2✔
74
  }
75

76
  @Override
77
  public Path getLegacyPropertiesFilePath() {
78

79
    return null;
×
80
  }
81

82
  @Override
83
  public VariableSource getSource() {
84

85
    if (this.source == null) {
3✔
86
      this.source = new VariableSource(getType(), getPropertiesFilePath());
9✔
87
    }
88
    return this.source;
3✔
89
  }
90

91
  /**
92
   * @param name the name of the variable to check.
93
   * @return {@code true} if the variable shall be exported, {@code false} otherwise.
94
   */
95
  protected boolean isExported(String name) {
96

97
    if (this.parent != null) {
3✔
98
      return this.parent.isExported(name);
5✔
99
    }
100
    return false;
2✔
101
  }
102

103
  @Override
104
  public final List<VariableLine> collectVariables() {
105

106
    return collectVariables(false);
4✔
107
  }
108

109
  @Override
110
  public final List<VariableLine> collectExportedVariables() {
111

112
    return collectVariables(true);
4✔
113
  }
114

115
  private final List<VariableLine> collectVariables(boolean onlyExported) {
116

117
    Map<String, VariableLine> variables = new HashMap<>();
4✔
118
    collectVariables(variables, onlyExported, this);
5✔
119
    return new ArrayList<>(variables.values());
6✔
120
  }
121

122
  /**
123
   * @param variables the {@link Map} where to add the names of the variables defined here as keys, and their corresponding source as value.
124
   */
125
  protected void collectVariables(Map<String, VariableLine> variables, boolean onlyExported, AbstractEnvironmentVariables resolver) {
126

127
    if (this.parent != null) {
3✔
128
      this.parent.collectVariables(variables, onlyExported, resolver);
6✔
129
    }
130
  }
1✔
131

132
  protected VariableLine createVariableLine(String name, boolean onlyExported, AbstractEnvironmentVariables resolver) {
133

134
    boolean export = resolver.isExported(name);
4✔
135
    if (!onlyExported || export) {
4✔
136
      String value = resolver.get(name, false);
5✔
137
      if (value != null) {
2✔
138
        return VariableLine.of(export, name, value, getSource());
7✔
139
      }
140
    }
141
    return null;
2✔
142
  }
143

144
  /**
145
   * @param propertiesFolderPath the {@link Path} to the folder containing the {@link #getPropertiesFilePath() properties file} of the child
146
   *     {@link EnvironmentVariables}.
147
   * @param type the {@link #getType() type}.
148
   * @return the new {@link EnvironmentVariables}.
149
   */
150
  public AbstractEnvironmentVariables extend(Path propertiesFolderPath, EnvironmentVariablesType type) {
151

152
    return new EnvironmentVariablesPropertiesFile(this, type, propertiesFolderPath, null, this.context);
10✔
153
  }
154

155
  /**
156
   * @return a new child {@link EnvironmentVariables} that will resolve variables recursively or this instance itself if already satisfied.
157
   */
158
  public EnvironmentVariables resolved() {
159

160
    return new EnvironmentVariablesResolved(this);
5✔
161
  }
162

163
  @Override
164
  public String resolve(String string, Object source) {
165
    return resolveRecursive(string, source, 0, this, new ResolveContext(source, string, false, VariableSyntax.CURLY));
14✔
166
  }
167

168
  @Override
169
  public String resolve(String string, Object source, boolean legacySupport) {
170

171
    return resolveRecursive(string, source, 0, this, new ResolveContext(source, string, legacySupport, null));
14✔
172
  }
173

174
  /**
175
   * This method is called recursively. This allows you to resolve variables that are defined by other variables.
176
   *
177
   * @param value the {@link String} that potentially contains variables in the syntax "${«variable«}". Those will be resolved by this method and replaced
178
   *     with their {@link #get(String) value}.
179
   * @param source the source where the {@link String} to resolve originates from. Should have a reasonable {@link Object#toString() string representation}
180
   *     that will be used in error or log messages if a variable could not be resolved.
181
   * @param recursion the current recursion level. This is used to interrupt endless recursion.
182
   * @param resolvedVars this is a reference to an object of {@link EnvironmentVariablesResolved} being the lowest level in the
183
   *     {@link EnvironmentVariablesType hierarchy} of variables. In case of a self-referencing variable {@code x} the resolving has to continue one level
184
   *     higher in the {@link EnvironmentVariablesType hierarchy} to avoid endless recursion. The {@link EnvironmentVariablesResolved} is then used if another
185
   *     variable {@code y} must be resolved, since resolving this variable has to again start at the lowest level. For example: For levels {@code l1, l2} with
186
   *     {@code l1 < l2} and {@code x=${x} foo} and {@code y=bar} defined at level {@code l1} and {@code x=test ${y}} defined at level {@code l2}, {@code x} is
187
   *     first resolved at level {@code l1} and then up the {@link EnvironmentVariablesType hierarchy} at {@code l2} to avoid endless recursion. However,
188
   *     {@code y} must be resolved starting from the lowest level in the {@link EnvironmentVariablesType hierarchy} and therefore
189
   *     {@link EnvironmentVariablesResolved} is used.
190
   * @param context the {@link ResolveContext}.
191
   * @return the given {@link String} with the variables resolved.
192
   */
193
  private String resolveRecursive(String value, Object source, int recursion, AbstractEnvironmentVariables resolvedVars, ResolveContext context) {
194

195
    if (value == null) {
2!
196
      return null;
×
197
    }
198
    if (recursion > MAX_RECURSION) {
3!
199
      throw new IllegalStateException(
×
200
          "Reached maximum recursion resolving " + value + " for root variable " + context.rootSrc + " with value '" + context.rootValue + "'.");
201
    }
202
    recursion++;
1✔
203

204
    String resolved;
205
    if (context.syntax == null) {
3✔
206
      resolved = resolveWithSyntax(value, source, recursion, resolvedVars, context, VariableSyntax.SQUARE);
9✔
207
      if (context.legacySupport) {
3!
208
        resolved = resolveWithSyntax(resolved, source, recursion, resolvedVars, context, VariableSyntax.CURLY);
10✔
209
      }
210
    } else {
211
      resolved = resolveWithSyntax(value, source, recursion, resolvedVars, context, context.syntax);
10✔
212
    }
213
    return resolved;
2✔
214
  }
215

216
  private String resolveWithSyntax(final String value, final Object src, final int recursion, final AbstractEnvironmentVariables resolvedVars,
217
      final ResolveContext context, final VariableSyntax syntax) {
218

219
    Matcher matcher = syntax.getPattern().matcher(value);
5✔
220
    if (!matcher.find()) {
3✔
221
      return value;
2✔
222
    }
223
    StringBuilder sb = new StringBuilder(value.length() + EXTRA_CAPACITY);
8✔
224
    do {
225
      String variableName = syntax.getVariable(matcher);
4✔
226
      String variableValue = resolvedVars.getValue(variableName, false);
5✔
227
      if (variableValue == null) {
2✔
228
        IdeLogLevel logLevel = IdeLogLevel.WARNING;
2✔
229
        if (context.legacySupport && (syntax == VariableSyntax.CURLY)) {
3!
230
          logLevel = IdeLogLevel.INFO;
×
231
        }
232
        String var = matcher.group();
3✔
233
        if (recursion > 1) {
3✔
234
          this.context.level(logLevel).log("Undefined variable {} in '{}' at '{}={}'", var, context.rootSrc, src, value);
27✔
235
        } else {
236
          this.context.level(logLevel).log("Undefined variable {} in '{}'", var, src);
17✔
237
        }
238
        continue;
1✔
239
      }
240
      EnvironmentVariables lowestFound = findVariable(variableName);
4✔
241
      if ((lowestFound == null) || !lowestFound.getFlat(variableName).equals(value)) {
8✔
242
        // looking for "variableName" starting from resolved upwards the hierarchy
243
        String replacement = resolvedVars.resolveRecursive(variableValue, variableName, recursion, resolvedVars, context);
8✔
244
        matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
6✔
245
      } else { // is self referencing
1✔
246
        // finding next occurrence of "variableName" up the hierarchy of EnvironmentVariablesType
247
        EnvironmentVariables next = lowestFound.getParent();
3✔
248
        while (next != null) {
2✔
249
          if (next.getFlat(variableName) != null) {
4✔
250
            break;
1✔
251
          }
252
          next = next.getParent();
4✔
253
        }
254
        if (next == null) {
2✔
255
          matcher.appendReplacement(sb, Matcher.quoteReplacement(SELF_REFERENCING_NOT_FOUND));
6✔
256
          continue;
1✔
257
        }
258
        // resolving a self referencing variable one level up the hierarchy of EnvironmentVariablesType, i.e. at "next",
259
        // to avoid endless recursion
260
        String replacement = ((AbstractEnvironmentVariables) next).resolveRecursive(next.getFlat(variableName), variableName, recursion, resolvedVars, context
11✔
261
        );
262
        matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
6✔
263

264
      }
265
    } while (matcher.find());
3✔
266
    matcher.appendTail(sb);
4✔
267

268
    String resolved = sb.toString();
3✔
269
    return resolved;
2✔
270
  }
271

272
  /**
273
   * Like {@link #get(String)} but with higher-level features including to resolve {@link IdeVariables} with their default values.
274
   *
275
   * @param name the name of the variable to get.
276
   * @param ignoreDefaultValue - {@code true} if the {@link VariableDefinition#getDefaultValue(IdeContext) default value} of a potential
277
   *     {@link VariableDefinition} shall be ignored, {@code false} to return default instead of {@code null}.
278
   * @return the value of the variable.
279
   */
280
  protected String getValue(String name, boolean ignoreDefaultValue) {
281

282
    VariableDefinition<?> var = IdeVariables.get(name);
3✔
283
    String value;
284
    if ((var != null) && var.isForceDefaultValue()) {
5✔
285
      value = var.getDefaultValueAsString(this.context);
6✔
286
    } else {
287
      value = this.parent.get(name, false);
6✔
288
    }
289
    if ((value == null) && (var != null)) {
4✔
290
      String key = var.getName();
3✔
291
      if (!name.equals(key)) {
4✔
292
        // try new name (e.g. IDE_TOOLS or IDE_HOME) if no value could be found by given legacy name (e.g.
293
        // DEVON_IDE_TOOLS or DEVON_IDE_HOME)
294
        value = this.parent.get(key, false);
6✔
295
      }
296
      if ((value == null) && !ignoreDefaultValue) {
4!
297
        value = var.getDefaultValueAsString(this.context);
5✔
298
      }
299
    }
300
    if ((value != null) && (value.startsWith("~/"))) {
6✔
301
      value = this.context.getUserHome() + value.substring(1);
9✔
302
    }
303
    return value;
2✔
304
  }
305

306
  @Override
307
  public String inverseResolve(String string, Object src, VariableSyntax syntax) {
308

309
    String result = string;
×
310
    // TODO add more variables to IdeVariables like JAVA_HOME
311
    for (VariableDefinition<?> variable : IdeVariables.VARIABLES) {
×
312
      if (variable != IdeVariables.PATH) {
×
313
        String name = variable.getName();
×
314
        String value = get(name);
×
315
        if (value == null) {
×
316
          value = variable.getDefaultValueAsString(this.context);
×
317
        }
318
        if (value != null) {
×
319
          result = result.replace(value, syntax.create(name));
×
320
        }
321
      }
322
    }
×
323
    if (!result.equals(string)) {
×
324
      this.context.trace("Inverse resolved '{}' to '{}' from {}.", string, result, src);
×
325
    }
326
    return result;
×
327
  }
328

329
  @Override
330
  public VersionIdentifier getToolVersion(String tool) {
331

332
    String variable = EnvironmentVariables.getToolVersionVariable(tool);
3✔
333
    String value = get(variable);
4✔
334
    if (value == null) {
2✔
335
      return VersionIdentifier.LATEST;
2✔
336
    } else if (value.isEmpty()) {
3✔
337
      this.context.warning("Variable {} is configured with empty value, please fix your configuration.", variable);
10✔
338
      return VersionIdentifier.LATEST;
2✔
339
    }
340
    VersionIdentifier version = VersionIdentifier.of(value);
3✔
341
    if (version == null) {
2!
342
      // can actually never happen, but for robustness
343
      version = VersionIdentifier.LATEST;
×
344
    }
345
    return version;
2✔
346
  }
347

348
  @Override
349
  public String toString() {
350

351
    return getSource().toString();
×
352
  }
353

354
  /**
355
   * Simple record for the immutable arguments of recursive resolve methods.
356
   *
357
   * @param rootSrc the root source where the {@link String} to resolve originates from.
358
   * @param rootValue the root value to resolve.
359
   * @param legacySupport flag for legacy support (see {@link #resolve(String, Object, boolean)}). Only considered if {@link #syntax()} is {@code null}.
360
   * @param syntax the explicit {@link VariableSyntax} to use.
361
   */
362
  private static record ResolveContext(Object rootSrc, String rootValue, boolean legacySupport, VariableSyntax syntax) {
15✔
363

364
  }
365

366
}
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