Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(15)

Side by Side Diff: utils/pub/version.dart

Issue 14297021: Move pub into sdk/lib/_internal. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Disallow package: imports of pub. Created 7 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « utils/pub/validator/utf8_readme.dart ('k') | utils/tests/pub/command_line_config.dart » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 /// Handles version numbers, following the [Semantic Versioning][semver] spec.
6 ///
7 /// [semver]: http://semver.org/
8 library version;
9
10 import 'dart:math';
11
12 import 'utils.dart';
13
14
15 /// Regex that matches a version number at the beginning of a string.
16 final _START_VERSION = new RegExp(
17 r'^' // Start at beginning.
18 r'(\d+).(\d+).(\d+)' // Version number.
19 r'(-([0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*))?' // Pre-release.
20 r'(\+([0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*))?'); // Build.
21
22 /// Like [_START_VERSION] but matches the entire string.
23 final _COMPLETE_VERSION = new RegExp("${_START_VERSION.pattern}\$");
24
25 /// Parses a comparison operator ("<", ">", "<=", or ">=") at the beginning of
26 /// a string.
27 final _START_COMPARISON = new RegExp(r"^[<>]=?");
28
29 /// A parsed semantic version number.
30 class Version implements Comparable<Version>, VersionConstraint {
31 /// No released version: i.e. "0.0.0".
32 static Version get none => new Version(0, 0, 0);
33 /// The major version number: "1" in "1.2.3".
34 final int major;
35
36 /// The minor version number: "2" in "1.2.3".
37 final int minor;
38
39 /// The patch version number: "3" in "1.2.3".
40 final int patch;
41
42 /// The pre-release identifier: "foo" in "1.2.3-foo". May be `null`.
43 final String preRelease;
44
45 /// The build identifier: "foo" in "1.2.3+foo". May be `null`.
46 final String build;
47
48 /// Creates a new [Version] object.
49 Version(this.major, this.minor, this.patch, {String pre, this.build})
50 : preRelease = pre {
51 if (major < 0) throw new ArgumentError(
52 'Major version must be non-negative.');
53 if (minor < 0) throw new ArgumentError(
54 'Minor version must be non-negative.');
55 if (patch < 0) throw new ArgumentError(
56 'Patch version must be non-negative.');
57 }
58
59 /// Creates a new [Version] by parsing [text].
60 factory Version.parse(String text) {
61 final match = _COMPLETE_VERSION.firstMatch(text);
62 if (match == null) {
63 throw new FormatException('Could not parse "$text".');
64 }
65
66 try {
67 int major = int.parse(match[1]);
68 int minor = int.parse(match[2]);
69 int patch = int.parse(match[3]);
70
71 String preRelease = match[5];
72 String build = match[8];
73
74 return new Version(major, minor, patch, pre: preRelease, build: build);
75 } on FormatException catch (ex) {
76 throw new FormatException('Could not parse "$text".');
77 }
78 }
79
80 /// Returns the primary version out of a list of candidates. This is the
81 /// highest-numbered stable (non-prerelease) version. If there are no stable
82 /// versions, it's just the highest-numbered version.
83 static Version primary(List<Version> versions) {
84 var primary;
85 for (var version in versions) {
86 if (primary == null || (!version.isPreRelease && primary.isPreRelease) ||
87 (version.isPreRelease == primary.isPreRelease && version > primary)) {
88 primary = version;
89 }
90 }
91 return primary;
92 }
93
94 bool operator ==(other) {
95 if (other is! Version) return false;
96 return compareTo(other) == 0;
97 }
98
99 bool operator <(Version other) => compareTo(other) < 0;
100 bool operator >(Version other) => compareTo(other) > 0;
101 bool operator <=(Version other) => compareTo(other) <= 0;
102 bool operator >=(Version other) => compareTo(other) >= 0;
103
104 bool get isAny => false;
105 bool get isEmpty => false;
106
107 /// Whether or not this is a pre-release version.
108 bool get isPreRelease => preRelease != null;
109
110 /// Tests if [other] matches this version exactly.
111 bool allows(Version other) => this == other;
112
113 VersionConstraint intersect(VersionConstraint other) {
114 if (other.isEmpty) return other;
115
116 // Intersect a version and a range.
117 if (other is VersionRange) return other.intersect(this);
118
119 // Intersecting two versions only works if they are the same.
120 if (other is Version) {
121 return this == other ? this : VersionConstraint.empty;
122 }
123
124 throw new ArgumentError(
125 'Unknown VersionConstraint type $other.');
126 }
127
128 int compareTo(Version other) {
129 if (major != other.major) return major.compareTo(other.major);
130 if (minor != other.minor) return minor.compareTo(other.minor);
131 if (patch != other.patch) return patch.compareTo(other.patch);
132
133 if (preRelease != other.preRelease) {
134 // Pre-releases always come before no pre-release string.
135 if (preRelease == null) return 1;
136 if (other.preRelease == null) return -1;
137
138 return _compareStrings(preRelease, other.preRelease);
139 }
140
141 if (build != other.build) {
142 // Builds always come after no build string.
143 if (build == null) return -1;
144 if (other.build == null) return 1;
145
146 return _compareStrings(build, other.build);
147 }
148
149 return 0;
150 }
151
152 int get hashCode => toString().hashCode;
153
154 String toString() {
155 var buffer = new StringBuffer();
156 buffer.write('$major.$minor.$patch');
157 if (preRelease != null) buffer.write('-$preRelease');
158 if (build != null) buffer.write('+$build');
159 return buffer.toString();
160 }
161
162 /// Compares the string part of two versions. This is used for the pre-release
163 /// and build version parts. This follows Rule 12. of the Semantic Versioning
164 /// spec.
165 int _compareStrings(String a, String b) {
166 var aParts = _splitParts(a);
167 var bParts = _splitParts(b);
168
169 for (int i = 0; i < max(aParts.length, bParts.length); i++) {
170 var aPart = (i < aParts.length) ? aParts[i] : null;
171 var bPart = (i < bParts.length) ? bParts[i] : null;
172
173 if (aPart != bPart) {
174 // Missing parts come before present ones.
175 if (aPart == null) return -1;
176 if (bPart == null) return 1;
177
178 if (aPart is int) {
179 if (bPart is int) {
180 // Compare two numbers.
181 return aPart.compareTo(bPart);
182 } else {
183 // Numbers come before strings.
184 return -1;
185 }
186 } else {
187 if (bPart is int) {
188 // Strings come after numbers.
189 return 1;
190 } else {
191 // Compare two strings.
192 return aPart.compareTo(bPart);
193 }
194 }
195 }
196 }
197 }
198
199 /// Splits a string of dot-delimited identifiers into their component parts.
200 /// Identifiers that are numeric are converted to numbers.
201 List _splitParts(String text) {
202 return text.split('.').map((part) {
203 try {
204 return int.parse(part);
205 } on FormatException catch (ex) {
206 // Not a number.
207 return part;
208 }
209 }).toList();
210 }
211 }
212
213 /// A [VersionConstraint] is a predicate that can determine whether a given
214 /// version is valid or not. For example, a ">= 2.0.0" constraint allows any
215 /// version that is "2.0.0" or greater. Version objects themselves implement
216 /// this to match a specific version.
217 abstract class VersionConstraint {
218 /// A [VersionConstraint] that allows all versions.
219 static VersionConstraint any = new VersionRange();
220
221 /// A [VersionConstraint] that allows no versions: i.e. the empty set.
222 static VersionConstraint empty = const _EmptyVersion();
223
224 /// Parses a version constraint. This string is either "any" or a series of
225 /// version parts. Each part can be one of:
226 ///
227 /// * A version string like `1.2.3`. In other words, anything that can be
228 /// parsed by [Version.parse()].
229 /// * A comparison operator (`<`, `>`, `<=`, or `>=`) followed by a version
230 /// string.
231 ///
232 /// Whitespace is ignored.
233 ///
234 /// Examples:
235 ///
236 /// any
237 /// 1.2.3-alpha
238 /// <=5.1.4
239 /// >2.0.4 <= 2.4.6
240 factory VersionConstraint.parse(String text) {
241 // Handle the "any" constraint.
242 if (text.trim() == "any") return new VersionRange();
243
244 var originalText = text;
245 var constraints = <VersionConstraint>[];
246
247 void skipWhitespace() {
248 text = text.trim();
249 }
250
251 // Try to parse and consume a version number.
252 Version matchVersion() {
253 var version = _START_VERSION.firstMatch(text);
254 if (version == null) return null;
255
256 text = text.substring(version.end);
257 return new Version.parse(version[0]);
258 }
259
260 // Try to parse and consume a comparison operator followed by a version.
261 VersionConstraint matchComparison() {
262 var comparison = _START_COMPARISON.firstMatch(text);
263 if (comparison == null) return null;
264
265 var op = comparison[0];
266 text = text.substring(comparison.end);
267 skipWhitespace();
268
269 var version = matchVersion();
270 if (version == null) {
271 throw new FormatException('Expected version number after "$op" in '
272 '"$originalText", got "$text".');
273 }
274
275 switch (op) {
276 case '<=':
277 return new VersionRange(max: version, includeMax: true);
278 case '<':
279 return new VersionRange(max: version, includeMax: false);
280 case '>=':
281 return new VersionRange(min: version, includeMin: true);
282 case '>':
283 return new VersionRange(min: version, includeMin: false);
284 }
285 }
286
287 while (true) {
288 skipWhitespace();
289 if (text.isEmpty) break;
290
291 var version = matchVersion();
292 if (version != null) {
293 constraints.add(version);
294 continue;
295 }
296
297 var comparison = matchComparison();
298 if (comparison != null) {
299 constraints.add(comparison);
300 continue;
301 }
302
303 // If we got here, we couldn't parse the remaining string.
304 throw new FormatException('Could not parse version "$originalText". '
305 'Unknown text at "$text".');
306 }
307
308 if (constraints.isEmpty) {
309 throw new FormatException('Cannot parse an empty string.');
310 }
311
312 return new VersionConstraint.intersection(constraints);
313 }
314
315 /// Creates a new version constraint that is the intersection of
316 /// [constraints]. It will only allow versions that all of those constraints
317 /// allow. If constraints is empty, then it returns a VersionConstraint that
318 /// allows all versions.
319 factory VersionConstraint.intersection(
320 Iterable<VersionConstraint> constraints) {
321 var constraint = new VersionRange();
322 for (var other in constraints) {
323 constraint = constraint.intersect(other);
324 }
325 return constraint;
326 }
327
328 /// Returns `true` if this constraint allows no versions.
329 bool get isEmpty;
330
331 /// Returns `true` if this constraint allows all versions.
332 bool get isAny;
333
334 /// Returns `true` if this constraint allows [version].
335 bool allows(Version version);
336
337 /// Creates a new [VersionConstraint] that only allows [Version]s allowed by
338 /// both this and [other].
339 VersionConstraint intersect(VersionConstraint other);
340 }
341
342 /// Constrains versions to a fall within a given range. If there is a minimum,
343 /// then this only allows versions that are at that minimum or greater. If there
344 /// is a maximum, then only versions less than that are allowed. In other words,
345 /// this allows `>= min, < max`.
346 class VersionRange implements VersionConstraint {
347 final Version min;
348 final Version max;
349 final bool includeMin;
350 final bool includeMax;
351
352 VersionRange({this.min, this.max,
353 this.includeMin: false, this.includeMax: false}) {
354 if (min != null && max != null && min > max) {
355 throw new ArgumentError(
356 'Minimum version ("$min") must be less than maximum ("$max").');
357 }
358 }
359
360 bool operator ==(other) {
361 if (other is! VersionRange) return false;
362
363 return min == other.min &&
364 max == other.max &&
365 includeMin == other.includeMin &&
366 includeMax == other.includeMax;
367 }
368
369 bool get isEmpty => false;
370
371 bool get isAny => !includeMin && !includeMax;
372
373 /// Tests if [other] matches falls within this version range.
374 bool allows(Version other) {
375 if (min != null && other < min) return false;
376 if (min != null && !includeMin && other == min) return false;
377 if (max != null && other > max) return false;
378 if (max != null && !includeMax && other == max) return false;
379 return true;
380 }
381
382 VersionConstraint intersect(VersionConstraint other) {
383 if (other.isEmpty) return other;
384
385 // A range and a Version just yields the version if it's in the range.
386 if (other is Version) {
387 return allows(other) ? other : VersionConstraint.empty;
388 }
389
390 if (other is VersionRange) {
391 // Intersect the two ranges.
392 var intersectMin = min;
393 var intersectIncludeMin = includeMin;
394 var intersectMax = max;
395 var intersectIncludeMax = includeMax;
396
397 if (other.min == null) {
398 // Do nothing.
399 } else if (intersectMin == null || intersectMin < other.min) {
400 intersectMin = other.min;
401 intersectIncludeMin = other.includeMin;
402 } else if (intersectMin == other.min && !other.includeMin) {
403 // The edges are the same, but one is exclusive, make it exclusive.
404 intersectIncludeMin = false;
405 }
406
407 if (other.max == null) {
408 // Do nothing.
409 } else if (intersectMax == null || intersectMax > other.max) {
410 intersectMax = other.max;
411 intersectIncludeMax = other.includeMax;
412 } else if (intersectMax == other.max && !other.includeMax) {
413 // The edges are the same, but one is exclusive, make it exclusive.
414 intersectIncludeMax = false;
415 }
416
417 if (intersectMin == null && intersectMax == null) {
418 // Open range.
419 return new VersionRange();
420 }
421
422 // If the range is just a single version.
423 if (intersectMin == intersectMax) {
424 // If both ends are inclusive, allow that version.
425 if (intersectIncludeMin && intersectIncludeMax) return intersectMin;
426
427 // Otherwise, no versions.
428 return VersionConstraint.empty;
429 }
430
431 if (intersectMin != null && intersectMax != null &&
432 intersectMin > intersectMax) {
433 // Non-overlapping ranges, so empty.
434 return VersionConstraint.empty;
435 }
436
437 // If we got here, there is an actual range.
438 return new VersionRange(min: intersectMin, max: intersectMax,
439 includeMin: intersectIncludeMin, includeMax: intersectIncludeMax);
440 }
441
442 throw new ArgumentError(
443 'Unknown VersionConstraint type $other.');
444 }
445
446 String toString() {
447 var buffer = new StringBuffer();
448
449 if (min != null) {
450 buffer.write(includeMin ? '>=' : '>');
451 buffer.write(min);
452 }
453
454 if (max != null) {
455 if (min != null) buffer.write(' ');
456 buffer.write(includeMax ? '<=' : '<');
457 buffer.write(max);
458 }
459
460 if (min == null && max == null) buffer.write('any');
461 return buffer.toString();
462 }
463 }
464
465 class _EmptyVersion implements VersionConstraint {
466 const _EmptyVersion();
467
468 bool get isEmpty => true;
469 bool get isAny => false;
470 bool allows(Version other) => false;
471 VersionConstraint intersect(VersionConstraint other) => this;
472 String toString() => '<empty>';
473 }
OLDNEW
« no previous file with comments | « utils/pub/validator/utf8_readme.dart ('k') | utils/tests/pub/command_line_config.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698