summaryrefslogtreecommitdiffstats
path: root/src/main/java/com/beust/jcommander/FuzzyMap.java
blob: 5f3939b8446d7b506b857dfa97cecfb474ce8d57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.beust.jcommander;

import com.beust.jcommander.internal.Maps;

import java.util.Map;

/**
 * Helper class to perform fuzzy key look ups: looking up case insensitive or
 * abbreviated keys.
 */
public class FuzzyMap {
  interface IKey {
    String getName();
  }

  public static <V> V findInMap(Map<? extends IKey, V> map, IKey name,
      boolean caseSensitive, boolean allowAbbreviations) {
    if (allowAbbreviations) {
      return findAbbreviatedValue(map, name, caseSensitive);
    } else {
      if (caseSensitive) {
        return map.get(name);
      } else {
        for (IKey c : map.keySet()) {
          if (c.getName().equalsIgnoreCase(name.getName())) {
            return map.get(c);
          }
        }
      }
    }
    return null;
  }

  private static <V> V findAbbreviatedValue(Map<? extends IKey, V> map, IKey name,
      boolean caseSensitive) {
    String string = name.getName();
    Map<String, V> results = Maps.newHashMap();
    for (IKey c : map.keySet()) {
      String n = c.getName();
      boolean match = (caseSensitive && n.startsWith(string))
          || ((! caseSensitive) && n.toLowerCase().startsWith(string.toLowerCase()));
      if (match) {
        results.put(n, map.get(c));
      }
    }

    V result;
    if (results.size() > 1) {
      throw new ParameterException("Ambiguous option: " + name
          + " matches " + results.keySet());
    } else if (results.size() == 1) {
      result = results.values().iterator().next();
    } else {
      result = null;
    }

    return result;
  }


}