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

devonfw / IDEasy / 11783967420

11 Nov 2024 06:14PM UTC coverage: 67.267% (+0.07%) from 67.195%
11783967420

push

github

web-flow
#745: fix loading and evaluation of variables (#746)

2457 of 3995 branches covered (61.5%)

Branch coverage included in aggregate %.

6398 of 9169 relevant lines covered (69.78%)

3.08 hits per line

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

78.11
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 VariableSource getSource() {
78

79
    if (this.source == null) {
3✔
80
      this.source = new VariableSource(getType(), getPropertiesFilePath());
9✔
81
    }
82
    return this.source;
3✔
83
  }
84

85
  /**
86
   * @param name the name of the variable to check.
87
   * @return {@code true} if the variable shall be exported, {@code false} otherwise.
88
   */
89
  protected boolean isExported(String name) {
90

91
    if (this.parent != null) {
3✔
92
      if (this.parent.isExported(name)) {
5!
93
        return true;
×
94
      }
95
    }
96
    return false;
2✔
97
  }
98

99
  @Override
100
  public final List<VariableLine> collectVariables() {
101

102
    return collectVariables(false);
4✔
103
  }
104

105
  @Override
106
  public final List<VariableLine> collectExportedVariables() {
107

108
    return collectVariables(true);
4✔
109
  }
110

111
  private final List<VariableLine> collectVariables(boolean onlyExported) {
112

113
    Map<String, VariableLine> variables = new HashMap<>();
4✔
114
    collectVariables(variables, onlyExported, this);
5✔
115
    return new ArrayList<>(variables.values());
6✔
116
  }
117

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

123
    if (this.parent != null) {
3✔
124
      this.parent.collectVariables(variables, onlyExported, resolver);
6✔
125
    }
126
  }
1✔
127

128
  protected VariableLine createVariableLine(String name, boolean onlyExported, AbstractEnvironmentVariables resolver) {
129

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

140
  /**
141
   * @param propertiesFilePath the {@link #getPropertiesFilePath() propertiesFilePath} of the child {@link EnvironmentVariables}.
142
   * @param type the {@link #getType() type}.
143
   * @return the new {@link EnvironmentVariables}.
144
   */
145
  public AbstractEnvironmentVariables extend(Path propertiesFilePath, EnvironmentVariablesType type) {
146

147
    return new EnvironmentVariablesPropertiesFile(this, type, propertiesFilePath, this.context);
9✔
148
  }
149

150
  /**
151
   * @return a new child {@link EnvironmentVariables} that will resolve variables recursively or this instance itself if already satisfied.
152
   */
153
  public EnvironmentVariables resolved() {
154

155
    return new EnvironmentVariablesResolved(this);
5✔
156
  }
157

158
  @Override
159
  public String resolve(String string, Object source) {
160
    return resolveRecursive(string, source, 0, this, new ResolveContext(source, string, false, VariableSyntax.CURLY));
14✔
161
  }
162

163
  @Override
164
  public String resolve(String string, Object source, boolean legacySupport) {
165

166
    return resolveRecursive(string, source, 0, this, new ResolveContext(source, string, legacySupport, null));
14✔
167
  }
168

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

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

199
    String resolved;
200
    if (context.syntax == null) {
3✔
201
      resolved = resolveWithSyntax(value, source, recursion, resolvedVars, context, VariableSyntax.SQUARE);
9✔
202
      if (context.legacySupport) {
3!
203
        resolved = resolveWithSyntax(value, source, recursion, resolvedVars, context, VariableSyntax.CURLY);
10✔
204
      }
205
    } else {
206
      resolved = resolveWithSyntax(value, source, recursion, resolvedVars, context, context.syntax);
10✔
207
    }
208
    return resolved;
2✔
209
  }
210

211
  private String resolveWithSyntax(final String value, final Object src, final int recursion, final AbstractEnvironmentVariables resolvedVars,
212
      final ResolveContext context, final VariableSyntax syntax) {
213

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

259
      }
260
    } while (matcher.find());
3✔
261
    matcher.appendTail(sb);
4✔
262

263
    String resolved = sb.toString();
3✔
264
    return resolved;
2✔
265
  }
266

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

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

301
  @Override
302
  public String inverseResolve(String string, Object src, VariableSyntax syntax) {
303

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

324
  @Override
325
  public VersionIdentifier getToolVersion(String tool) {
326

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

343
  @Override
344
  public String toString() {
345

346
    return getSource().toString();
×
347
  }
348

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

359
  }
360

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