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

devonfw / IDEasy / 9907372175

12 Jul 2024 11:49AM UTC coverage: 61.142% (-0.02%) from 61.162%
9907372175

push

github

hohwille
fixed tests

1997 of 3595 branches covered (55.55%)

Branch coverage included in aggregate %.

5296 of 8333 relevant lines covered (63.55%)

2.8 hits per line

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

79.27
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.Collection;
6
import java.util.HashSet;
7
import java.util.List;
8
import java.util.Set;
9
import java.util.regex.Matcher;
10

11
import com.devonfw.tools.ide.context.IdeContext;
12
import com.devonfw.tools.ide.log.IdeLogLevel;
13
import com.devonfw.tools.ide.variable.IdeVariables;
14
import com.devonfw.tools.ide.variable.VariableDefinition;
15
import com.devonfw.tools.ide.variable.VariableSyntax;
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;
2✔
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(
×
197
          "Reached maximum recursion resolving " + value + " for root variable " + context.rootSrc + " with value '" + context.rootValue + "'.");
198
    }
199
    recursion++;
1✔
200

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

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

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

261
      }
262
    } while (matcher.find());
3✔
263
    matcher.appendTail(sb);
4✔
264

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

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

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

303
  @Override
304
  public String inverseResolve(String string, Object src, VariableSyntax syntax) {
305

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

326
  @Override
327
  public String toString() {
328

329
    return getSource();
×
330
  }
331

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

342
  }
343

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