Skip to content
Permalink
Browse files
[JENKINS-27203] Fix handling of environment variables
Replace longer variables first to avoid replacing a
partial long name with a short name.

Example:
 - NODE = abc
 - NODE_ID = 123

Result "abc_ID" instead of "123"
  • Loading branch information
misery committed Mar 2, 2015
1 parent 5276576 commit 2542acd21fed0ee724ba5f3cc13213cfcca7f55b
Showing with 20 additions and 3 deletions.
  1. +16 −1 src/main/java/hudson/plugins/cmake/EnvVarReplacer.java
  2. +4 −2 src/test/java/hudson/plugins/cmake/EnvVarReplacerTest.java
@@ -1,12 +1,27 @@
package hudson.plugins.cmake;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;

class StringLengthComparator implements Comparator<String>
{
@Override
public int compare(String lhs, String rhs)
{
return rhs.length() - lhs.length();
}
}

public class EnvVarReplacer {

public static String replace(String stringContainingEnvVars, Map<String, String> envVars) {
Set<String> keys = envVars.keySet();
List<String> keys = new ArrayList<String>(envVars.keySet());
Collections.sort(keys, new StringLengthComparator());

for (String key : keys) {
stringContainingEnvVars =
stringContainingEnvVars.replaceAll("\\$" + key, envVars.get(key));
@@ -15,12 +15,14 @@

@Test
public void checkReplacement() throws Exception {
String strWithEnvVars = "Is $HOME in $PATH?";
String desired = "Is /home/jonnyro in /usr/bin/;/usr/local/bin/?";
String strWithEnvVars = "Is $HOME in $PATH? $NODE $NODE_ID";
String desired = "Is /home/jonnyro in /usr/bin/;/usr/local/bin/? abc123 987";
HashMap<String,String> envVars = new HashMap<String,String>();

envVars.put("HOME","/home/jonnyro");
envVars.put("PATH","/usr/bin/;/usr/local/bin/");
envVars.put("NODE","abc123");
envVars.put("NODE_ID","987");

EnvVarReplacer e = new EnvVarReplacer();

0 comments on commit 2542acd

Please sign in to comment.