blob: 07616167dc94b4d4326c8cc0bcb375507ee7ff6b [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
44 public String toString() {
45 if (high == low)
46 return high.toString();
47
48 StringBuilder sb = new StringBuilder();
49 sb.append(start);
50 sb.append(low);
51 sb.append(',');
52 sb.append(high);
53 sb.append(end);
54 return sb.toString();
55 }
56
57 public Version getLow() {
58 return low;
59 }
60
61 public Version getHigh() {
62 return high;
63 }
64
65 public boolean includes(Version v) {
Stuart McCulloch2286f232012-06-15 13:27:53 +000066 if (!isRange()) {
67 return low.compareTo(v) <= 0;
Stuart McCullochbb014372012-06-07 21:57:32 +000068 }
69 if (includeLow()) {
70 if (v.compareTo(low) < 0)
71 return false;
72 } else if (v.compareTo(low) <= 0)
73 return false;
74
75 if (includeHigh()) {
76 if (v.compareTo(high) > 0)
77 return false;
78 } else if (v.compareTo(high) >= 0)
79 return false;
Stuart McCulloch2286f232012-06-15 13:27:53 +000080
Stuart McCullochbb014372012-06-07 21:57:32 +000081 return true;
82 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000083
84 public Iterable<Version> filter(final Iterable<Version> versions) {
Stuart McCullochbb014372012-06-07 21:57:32 +000085 List<Version> list = new ArrayList<Version>();
Stuart McCulloch2286f232012-06-15 13:27:53 +000086 for (Version v : versions) {
87 if (includes(v))
Stuart McCullochbb014372012-06-07 21:57:32 +000088 list.add(v);
89 }
90 return list;
91 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000092
Stuart McCullochbb014372012-06-07 21:57:32 +000093}