blob: 8c9a8ddbe76868657faaa3b3bed4ae612005bb5f [file] [log] [blame]
Stuart McCulloch6a046662012-07-19 13:11:20 +00001package aQute.bnd.version;
Stuart McCullochbb014372012-06-07 21:57:32 +00002
3import java.util.*;
4import java.util.regex.*;
5
6public class VersionRange {
7 Version high;
8 Version low;
9 char start = '[';
10 char end = ']';
11
Stuart McCulloch2286f232012-06-15 13:27:53 +000012 static Pattern RANGE = Pattern.compile("(\\(|\\[)\\s*(" + Version.VERSION_STRING + ")\\s*,\\s*("
13 + Version.VERSION_STRING + ")\\s*(\\)|\\])");
Stuart McCullochbb014372012-06-07 21:57:32 +000014
15 public VersionRange(String string) {
16 string = string.trim();
17 Matcher m = RANGE.matcher(string);
18 if (m.matches()) {
19 start = m.group(1).charAt(0);
20 String v1 = m.group(2);
21 String v2 = m.group(10);
22 low = new Version(v1);
23 high = new Version(v2);
24 end = m.group(18).charAt(0);
25 if (low.compareTo(high) > 0)
Stuart McCulloch2286f232012-06-15 13:27:53 +000026 throw new IllegalArgumentException("Low Range is higher than High Range: " + low + "-" + high);
Stuart McCullochbb014372012-06-07 21:57:32 +000027
28 } else
29 high = low = new Version(string);
30 }
31
32 public boolean isRange() {
33 return high != low;
34 }
35
36 public boolean includeLow() {
37 return start == '[';
38 }
39
40 public boolean includeHigh() {
41 return end == ']';
42 }
43
Stuart McCulloch55d4dfe2012-08-07 10:57:21 +000044 @Override
Stuart McCullochbb014372012-06-07 21:57:32 +000045 public String toString() {
46 if (high == low)
47 return high.toString();
48
49 StringBuilder sb = new StringBuilder();
50 sb.append(start);
51 sb.append(low);
52 sb.append(',');
53 sb.append(high);
54 sb.append(end);
55 return sb.toString();
56 }
57
58 public Version getLow() {
59 return low;
60 }
61
62 public Version getHigh() {
63 return high;
64 }
65
66 public boolean includes(Version v) {
Stuart McCulloch2286f232012-06-15 13:27:53 +000067 if (!isRange()) {
68 return low.compareTo(v) <= 0;
Stuart McCullochbb014372012-06-07 21:57:32 +000069 }
70 if (includeLow()) {
71 if (v.compareTo(low) < 0)
72 return false;
73 } else if (v.compareTo(low) <= 0)
74 return false;
75
76 if (includeHigh()) {
77 if (v.compareTo(high) > 0)
78 return false;
79 } else if (v.compareTo(high) >= 0)
80 return false;
Stuart McCulloch2286f232012-06-15 13:27:53 +000081
Stuart McCullochbb014372012-06-07 21:57:32 +000082 return true;
83 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000084
85 public Iterable<Version> filter(final Iterable<Version> versions) {
Stuart McCullochbb014372012-06-07 21:57:32 +000086 List<Version> list = new ArrayList<Version>();
Stuart McCulloch2286f232012-06-15 13:27:53 +000087 for (Version v : versions) {
88 if (includes(v))
Stuart McCullochbb014372012-06-07 21:57:32 +000089 list.add(v);
90 }
91 return list;
92 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000093
Stuart McCullochbb014372012-06-07 21:57:32 +000094}