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

devonfw / IDEasy / 9660998058

25 Jun 2024 10:43AM UTC coverage: 60.42% (-0.06%) from 60.475%
9660998058

push

github

web-flow
#171: support for multiple VariableSyntax styles (#407)

1898 of 3450 branches covered (55.01%)

Branch coverage included in aggregate %.

4985 of 7942 relevant lines covered (62.77%)

2.74 hits per line

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

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

3
import com.devonfw.tools.ide.context.IdeContext;
4
import com.devonfw.tools.ide.log.IdeLogLevel;
5
import com.devonfw.tools.ide.variable.IdeVariables;
6
import com.devonfw.tools.ide.variable.VariableDefinition;
7
import com.devonfw.tools.ide.variable.VariableSyntax;
8

9
import java.nio.file.Path;
10
import java.util.ArrayList;
11
import java.util.Collection;
12
import java.util.HashSet;
13
import java.util.List;
14
import java.util.Set;
15
import java.util.regex.Matcher;
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 String 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 String getSource() {
78

79
    if (this.source == null) {
3✔
80
      this.source = getType().toString();
5✔
81
      Path propertiesPath = getPropertiesFilePath();
3✔
82
      if (propertiesPath != null) {
2✔
83
        this.source = this.source + "@" + propertiesPath;
6✔
84
      }
85
    }
86
    return this.source;
3✔
87
  }
88

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

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

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

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

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

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

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

117
    Set<String> variableNames = new HashSet<>();
4✔
118
    collectVariables(variableNames);
3✔
119
    List<VariableLine> variables = new ArrayList<>(variableNames.size());
6✔
120
    for (String name : variableNames) {
10✔
121
      boolean export = isExported(name);
4✔
122
      if (!onlyExported || export) {
4✔
123
        String value = get(name, false);
5✔
124
        if (value != null) {
2✔
125
          variables.add(VariableLine.of(export, name, value));
7✔
126
        }
127
      }
128
    }
1✔
129
    return variables;
2✔
130
  }
131

132
  /**
133
   * @param variables the {@link Set} where to add the names of the variables defined here.
134
   */
135
  protected void collectVariables(Set<String> variables) {
136

137
    if (this.parent != null) {
3✔
138
      this.parent.collectVariables(variables);
4✔
139
    }
140
  }
1✔
141

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

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

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

157
    return new EnvironmentVariablesResolved(this);
5✔
158
  }
159

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

165
  @Override
166
  public String resolve(String string, Object source, boolean legacySupport) {
167

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

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

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

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

212
  private String resolveWithSyntax(final String value, final Object src, final int recursion, final AbstractEnvironmentVariables resolvedVars, 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 String toString() {
326

327
    return getSource();
×
328
  }
329

330
  /**
331
   * Simple record for the immutable arguments of recursive resolve methods.
332
   *
333
   * @param rootSrc       the root source where the {@link String} to resolve originates from.
334
   * @param rootValue     the root value to resolve.
335
   * @param legacySupport flag for legacy support (see {@link #resolve(String, Object, boolean)}). Only considered if {@link #syntax()} is {@code null}.
336
   * @param syntax        the explicit {@link VariableSyntax} to use.
337
   */
338
  private static record ResolveContext(Object rootSrc, String rootValue, boolean legacySupport, VariableSyntax syntax) {
15✔
339

340
  }
341

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

© 2026 Coveralls, Inc