Newer
Older
dub_jkp / source / dub / dependency.d
  1. /**
  2. Dependency specification functionality.
  3.  
  4. Copyright: © 2012-2013 Matthias Dondorff, © 2012-2016 Sönke Ludwig
  5. License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
  6. Authors: Matthias Dondorff, Sönke Ludwig
  7. */
  8. module dub.dependency;
  9.  
  10. import dub.internal.utils;
  11. import dub.internal.vibecompat.core.file;
  12. import dub.internal.vibecompat.data.json;
  13. import dub.internal.vibecompat.inet.path;
  14. import dub.package_;
  15. import dub.semver;
  16. import dub.internal.logging;
  17.  
  18. import std.algorithm;
  19. import std.array;
  20. import std.exception;
  21. import std.string;
  22. import std.sumtype;
  23.  
  24.  
  25. /** Encapsulates the name of a package along with its dependency specification.
  26. */
  27. struct PackageDependency {
  28. /// Name of the referenced package.
  29. string name;
  30.  
  31. /// Dependency specification used to select a particular version of the package.
  32. Dependency spec;
  33. }
  34.  
  35. /**
  36. Represents a dependency specification.
  37.  
  38. A dependency specification either represents a specific version or version
  39. range, or a path to a package. In addition to that it has `optional` and
  40. `default_` flags to control how non-mandatory dependencies are handled. The
  41. package name is notably not part of the dependency specification.
  42. */
  43. struct Dependency {
  44. /// We currently support 3 'types'
  45. private alias Value = SumType!(VersionRange, NativePath, Repository);
  46.  
  47. /// Used by `toString`
  48. private static immutable string[] BooleanOptions = [ "optional", "default" ];
  49.  
  50. // Shortcut to create >=0.0.0
  51. private enum ANY_IDENT = "*";
  52.  
  53. private Value m_value;
  54. private bool m_optional;
  55. private bool m_default;
  56.  
  57. /// A Dependency, which matches every valid version.
  58. static @property Dependency any() @safe { return Dependency(VersionRange.Any); }
  59.  
  60. /// An invalid dependency (with no possible version matches).
  61. static @property Dependency invalid() @safe
  62. {
  63. return Dependency(VersionRange.Invalid);
  64. }
  65.  
  66. /** Constructs a new dependency specification that matches a specific
  67. path.
  68. */
  69. this(NativePath path) @safe
  70. {
  71. this.m_value = path;
  72. }
  73.  
  74. /** Constructs a new dependency specification that matches a specific
  75. Git reference.
  76. */
  77. this(Repository repository) @safe
  78. {
  79. this.m_value = repository;
  80. }
  81.  
  82. /** Constructs a new dependency specification from a string
  83.  
  84. See the `versionSpec` property for a description of the accepted
  85. contents of that string.
  86. */
  87. this(string spec) @safe
  88. {
  89. this(VersionRange.fromString(spec));
  90. }
  91.  
  92. /** Constructs a new dependency specification that matches a specific
  93. version.
  94. */
  95. this(const Version ver) @safe
  96. {
  97. this(VersionRange(ver, ver));
  98. }
  99.  
  100. /// Construct a version from a range of possible values
  101. this (VersionRange rng) @safe
  102. {
  103. this.m_value = rng;
  104. }
  105.  
  106. deprecated("Instantiate the `Repository` struct with the string directy")
  107. this(Repository repository, string spec) @safe
  108. {
  109. assert(repository.m_ref is null);
  110. repository.m_ref = spec;
  111. this(repository);
  112. }
  113.  
  114. /// If set, overrides any version based dependency selection.
  115. @property void path(NativePath value) @trusted
  116. {
  117. this.m_value = value;
  118. }
  119. /// ditto
  120. @property NativePath path() const @safe
  121. {
  122. return this.m_value.match!(
  123. (const NativePath p) => p,
  124. ( any ) => NativePath.init,
  125. );
  126. }
  127.  
  128. /// If set, overrides any version based dependency selection.
  129. @property void repository(Repository value) @trusted
  130. {
  131. this.m_value = value;
  132. }
  133. /// ditto
  134. @property Repository repository() const @safe
  135. {
  136. return this.m_value.match!(
  137. (const Repository p) => p,
  138. ( any ) => Repository.init,
  139. );
  140. }
  141.  
  142. /// Determines if the dependency is required or optional.
  143. @property bool optional() const scope @safe pure nothrow @nogc
  144. {
  145. return m_optional;
  146. }
  147. /// ditto
  148. @property void optional(bool optional) scope @safe pure nothrow @nogc
  149. {
  150. m_optional = optional;
  151. }
  152.  
  153. /// Determines if an optional dependency should be chosen by default.
  154. @property bool default_() const scope @safe pure nothrow @nogc
  155. {
  156. return m_default;
  157. }
  158. /// ditto
  159. @property void default_(bool value) scope @safe pure nothrow @nogc
  160. {
  161. m_default = value;
  162. }
  163.  
  164. /// Returns true $(I iff) the version range only matches a specific version.
  165. @property bool isExactVersion() const scope @safe
  166. {
  167. return this.m_value.match!(
  168. (NativePath v) => false,
  169. (Repository v) => false,
  170. (VersionRange v) => v.isExactVersion(),
  171. );
  172. }
  173.  
  174. /// Returns the exact version matched by the version range.
  175. @property Version version_() const @safe {
  176. auto range = this.m_value.match!(
  177. (NativePath p) => assert(0),
  178. (Repository r) => assert(0),
  179. (VersionRange v) => v,
  180. );
  181. enforce(range.isExactVersion(),
  182. "Dependency "~range.toString()~" is no exact version.");
  183. return range.m_versA;
  184. }
  185.  
  186. /// Sets/gets the matching version range as a specification string.
  187. deprecated("Create a new `Dependency` instead and provide a `VersionRange`")
  188. @property void versionSpec(string ves) @trusted
  189. {
  190. this.m_value = VersionRange.fromString(ves);
  191. }
  192.  
  193. /// ditto
  194. deprecated("Use `Dependency.visit` and match `VersionRange`instead")
  195. @property string versionSpec() const @safe {
  196. return this.m_value.match!(
  197. (const NativePath p) => ANY_IDENT,
  198. (const Repository r) => r.m_ref,
  199. (const VersionRange p) => p.toString(),
  200. );
  201. }
  202.  
  203. /** Returns a modified dependency that gets mapped to a given path.
  204.  
  205. This function will return an unmodified `Dependency` if it is not path
  206. based. Otherwise, the given `path` will be prefixed to the existing
  207. path.
  208. */
  209. Dependency mapToPath(NativePath path) const @trusted {
  210. // NOTE Path is @system in vibe.d 0.7.x and in the compatibility layer
  211. return this.m_value.match!(
  212. (NativePath v) {
  213. if (v.empty || v.absolute) return this;
  214. return Dependency(path ~ v);
  215. },
  216. (Repository v) => this,
  217. (VersionRange v) => this,
  218. );
  219. }
  220.  
  221. /** Returns a human-readable string representation of the dependency
  222. specification.
  223. */
  224. string toString() const scope @trusted {
  225. // Trusted because `SumType.match` doesn't seem to support `scope`
  226.  
  227. string Stringifier (T, string pre = null) (const T v)
  228. {
  229. const bool extra = this.optional || this.default_;
  230. return format("%s%s%s%-(%s, %)%s",
  231. pre, v,
  232. extra ? " (" : "",
  233. BooleanOptions[!this.optional .. 1 + this.default_],
  234. extra ? ")" : "");
  235. }
  236.  
  237. return this.m_value.match!(
  238. Stringifier!Repository,
  239. Stringifier!(NativePath, "@"),
  240. Stringifier!VersionRange
  241. );
  242. }
  243.  
  244. /** Returns a JSON representation of the dependency specification.
  245.  
  246. Simple specifications will be represented as a single specification
  247. string (`versionSpec`), while more complex specifications will be
  248. represented as a JSON object with optional "version", "path", "optional"
  249. and "default" fields.
  250.  
  251. Params:
  252. selections = We are serializing `dub.selections.json`, don't write out
  253. `optional` and `default`.
  254. */
  255. Json toJson(bool selections = false) const @safe
  256. {
  257. // NOTE Path and Json is @system in vibe.d 0.7.x and in the compatibility layer
  258. static void initJson(ref Json j, bool opt, bool def, bool s = selections)
  259. {
  260. j = Json.emptyObject;
  261. if (!s && opt) j["optional"] = true;
  262. if (!s && def) j["default"] = true;
  263. }
  264.  
  265. Json json;
  266. this.m_value.match!(
  267. (const NativePath v) @trusted {
  268. initJson(json, optional, default_);
  269. json["path"] = path.toString();
  270. },
  271.  
  272. (const Repository v) @trusted {
  273. initJson(json, optional, default_);
  274. json["repository"] = v.toString();
  275. json["version"] = v.m_ref;
  276. },
  277.  
  278. (const VersionRange v) @trusted {
  279. if (!selections && (optional || default_))
  280. {
  281. initJson(json, optional, default_);
  282. json["version"] = v.toString();
  283. }
  284. else
  285. json = Json(v.toString());
  286. },
  287. );
  288. return json;
  289. }
  290.  
  291. @trusted unittest {
  292. Dependency d = Dependency("==1.0.0");
  293. assert(d.toJson() == Json("1.0.0"), "Failed: " ~ d.toJson().toPrettyString());
  294. d = fromJson((fromJson(d.toJson())).toJson());
  295. assert(d == Dependency("1.0.0"));
  296. assert(d.toJson() == Json("1.0.0"), "Failed: " ~ d.toJson().toPrettyString());
  297. }
  298.  
  299. @trusted unittest {
  300. Dependency dependency = Dependency(Repository("git+http://localhost", "1.0.0"));
  301. Json expected = Json([
  302. "repository": Json("git+http://localhost"),
  303. "version": Json("1.0.0")
  304. ]);
  305. assert(dependency.toJson() == expected, "Failed: " ~ dependency.toJson().toPrettyString());
  306. }
  307.  
  308. @trusted unittest {
  309. Dependency d = Dependency(NativePath("dir"));
  310. Json expected = Json([ "path": Json("dir") ]);
  311. assert(d.toJson() == expected, "Failed: " ~ d.toJson().toPrettyString());
  312. }
  313.  
  314. /** Constructs a new `Dependency` from its JSON representation.
  315.  
  316. See `toJson` for a description of the JSON format.
  317. */
  318. static Dependency fromJson(Json verspec)
  319. @trusted { // NOTE Path and Json is @system in vibe.d 0.7.x and in the compatibility layer
  320. Dependency dep;
  321. if( verspec.type == Json.Type.object ){
  322. if( auto pp = "path" in verspec ) {
  323. if (auto pv = "version" in verspec)
  324. logDiagnostic("Ignoring version specification (%s) for path based dependency %s", pv.get!string, pp.get!string);
  325.  
  326. dep = Dependency.any;
  327. dep.path = NativePath(verspec["path"].get!string);
  328. } else if (auto repository = "repository" in verspec) {
  329. enforce("version" in verspec, "No version field specified!");
  330. enforce(repository.length > 0, "No repository field specified!");
  331.  
  332. dep = Dependency(Repository(
  333. repository.get!string, verspec["version"].get!string));
  334. } else {
  335. enforce("version" in verspec, "No version field specified!");
  336. auto ver = verspec["version"].get!string;
  337. // Using the string to be able to specify a range of versions.
  338. dep = Dependency(ver);
  339. }
  340.  
  341. if (auto po = "optional" in verspec) dep.optional = po.get!bool;
  342. if (auto po = "default" in verspec) dep.default_ = po.get!bool;
  343. } else {
  344. // canonical "package-id": "version"
  345. dep = Dependency(verspec.get!string);
  346. }
  347. return dep;
  348. }
  349.  
  350. @trusted unittest {
  351. assert(fromJson(parseJsonString("\">=1.0.0 <2.0.0\"")) == Dependency(">=1.0.0 <2.0.0"));
  352. Dependency parsed = fromJson(parseJsonString(`
  353. {
  354. "version": "2.0.0",
  355. "optional": true,
  356. "default": true,
  357. "path": "path/to/package"
  358. }
  359. `));
  360. Dependency d = Dependency.any; // supposed to ignore the version spec
  361. d.optional = true;
  362. d.default_ = true;
  363. d.path = NativePath("path/to/package");
  364. assert(d == parsed);
  365. // optional and path not checked by opEquals.
  366. assert(d.optional == parsed.optional);
  367. assert(d.default_ == parsed.default_);
  368. assert(d.path == parsed.path);
  369. }
  370.  
  371. /** Compares dependency specifications.
  372.  
  373. These methods are suitable for equality comparisons, as well as for
  374. using `Dependency` as a key in hash or tree maps.
  375. */
  376. bool opEquals(in Dependency o) const scope @safe {
  377. return this.m_value == o.m_value
  378. && o.m_optional == m_optional && o.m_default == m_default;
  379. }
  380.  
  381. /// ditto
  382. int opCmp(in Dependency o) const @safe {
  383. alias ResultMatch = match!(
  384. (VersionRange r1, VersionRange r2) => r1.opCmp(r2),
  385. (_1, _2) => 0,
  386. );
  387. if (auto result = ResultMatch(this.m_value, o.m_value))
  388. return result;
  389. if (m_optional != o.m_optional) return m_optional ? -1 : 1;
  390. return 0;
  391. }
  392.  
  393. /** Determines if this dependency specification is valid.
  394.  
  395. A specification is valid if it can match at least one version.
  396. */
  397. bool valid() const @safe {
  398. return this.m_value.match!(
  399. (NativePath v) => true,
  400. (Repository v) => true,
  401. (VersionRange v) => v.isValid(),
  402. );
  403. }
  404.  
  405. /** Determines if this dependency specification matches arbitrary versions.
  406.  
  407. This is true in particular for the `any` constant.
  408. */
  409. deprecated("Use `VersionRange.matchesAny` directly")
  410. bool matchesAny() const scope @safe {
  411. return this.m_value.match!(
  412. (NativePath v) => true,
  413. (Repository v) => true,
  414. (VersionRange v) => v.matchesAny(),
  415. );
  416. }
  417.  
  418. /** Tests if the specification matches a specific version.
  419. */
  420. bool matches(string vers, VersionMatchMode mode = VersionMatchMode.standard) const @safe
  421. {
  422. return matches(Version(vers), mode);
  423. }
  424. /// ditto
  425. bool matches(in Version v, VersionMatchMode mode = VersionMatchMode.standard) const @safe {
  426. return this.m_value.match!(
  427. (NativePath i) => true,
  428. (Repository i) => true,
  429. (VersionRange i) => i.matchesAny() || i.matches(v, mode),
  430. );
  431. }
  432.  
  433. /** Merges two dependency specifications.
  434.  
  435. The result is a specification that matches the intersection of the set
  436. of versions matched by the individual specifications. Note that this
  437. result can be invalid (i.e. not match any version).
  438. */
  439. Dependency merge(ref const(Dependency) o) const @trusted {
  440. alias Merger = match!(
  441. (const NativePath a, const NativePath b) => a == b ? this : invalid,
  442. (const NativePath a, any ) => o,
  443. ( any , const NativePath b) => this,
  444.  
  445. (const Repository a, const Repository b) => a.m_ref == b.m_ref ? this : invalid,
  446. (const Repository a, any ) => this,
  447. ( any , const Repository b) => o,
  448.  
  449. (const VersionRange a, const VersionRange b) {
  450. if (a.matchesAny()) return o;
  451. if (b.matchesAny()) return this;
  452.  
  453. VersionRange copy = a;
  454. copy.merge(b);
  455. if (!copy.isValid()) return invalid;
  456. return Dependency(copy);
  457. }
  458. );
  459.  
  460. Dependency ret = Merger(this.m_value, o.m_value);
  461. ret.m_optional = m_optional && o.m_optional;
  462. return ret;
  463. }
  464. }
  465.  
  466. /// Allow direct access to the underlying dependency
  467. public auto visit (Handlers...) (const auto ref Dependency dep)
  468. {
  469. return dep.m_value.match!(Handlers);
  470. }
  471.  
  472. //// Ditto
  473. public auto visit (Handlers...) (auto ref Dependency dep)
  474. {
  475. return dep.m_value.match!(Handlers);
  476. }
  477.  
  478.  
  479. unittest {
  480. Dependency a = Dependency(">=1.1.0"), b = Dependency(">=1.3.0");
  481. assert (a.merge(b).valid() && a.merge(b).toString() == ">=1.3.0", a.merge(b).toString());
  482.  
  483. assertThrown(Dependency("<=2.0.0 >=1.0.0"));
  484. assertThrown(Dependency(">=2.0.0 <=1.0.0"));
  485.  
  486. a = Dependency(">=1.0.0 <=5.0.0"); b = Dependency(">=2.0.0");
  487. assert (a.merge(b).valid() && a.merge(b).toString() == ">=2.0.0 <=5.0.0", a.merge(b).toString());
  488.  
  489. assertThrown(a = Dependency(">1.0.0 ==5.0.0"), "Construction is invalid");
  490.  
  491. a = Dependency(">1.0.0"); b = Dependency("<2.0.0");
  492. assert (a.merge(b).valid(), a.merge(b).toString());
  493. assert (a.merge(b).toString() == ">1.0.0 <2.0.0", a.merge(b).toString());
  494.  
  495. a = Dependency(">2.0.0"); b = Dependency("<1.0.0");
  496. assert (!(a.merge(b)).valid(), a.merge(b).toString());
  497.  
  498. a = Dependency(">=2.0.0"); b = Dependency("<=1.0.0");
  499. assert (!(a.merge(b)).valid(), a.merge(b).toString());
  500.  
  501. a = Dependency("==2.0.0"); b = Dependency("==1.0.0");
  502. assert (!(a.merge(b)).valid(), a.merge(b).toString());
  503.  
  504. a = Dependency("1.0.0"); b = Dependency("==1.0.0");
  505. assert (a == b);
  506.  
  507. a = Dependency("<=2.0.0"); b = Dependency("==1.0.0");
  508. Dependency m = a.merge(b);
  509. assert (m.valid(), m.toString());
  510. assert (m.matches(Version("1.0.0")));
  511. assert (!m.matches(Version("1.1.0")));
  512. assert (!m.matches(Version("0.0.1")));
  513.  
  514.  
  515. // branches / head revisions
  516. a = Dependency(Version.masterBranch);
  517. assert(a.valid());
  518. assert(a.matches(Version.masterBranch));
  519. b = Dependency(Version.masterBranch);
  520. m = a.merge(b);
  521. assert(m.matches(Version.masterBranch));
  522.  
  523. //assertThrown(a = Dependency(Version.MASTER_STRING ~ " <=1.0.0"), "Construction invalid");
  524. assertThrown(a = Dependency(">=1.0.0 " ~ Version.masterBranch.toString()), "Construction invalid");
  525.  
  526. immutable string branch1 = Version.branchPrefix ~ "Branch1";
  527. immutable string branch2 = Version.branchPrefix ~ "Branch2";
  528.  
  529. //assertThrown(a = Dependency(branch1 ~ " " ~ branch2), "Error: '" ~ branch1 ~ " " ~ branch2 ~ "' succeeded");
  530. //assertThrown(a = Dependency(Version.MASTER_STRING ~ " " ~ branch1), "Error: '" ~ Version.MASTER_STRING ~ " " ~ branch1 ~ "' succeeded");
  531.  
  532. a = Dependency(branch1);
  533. b = Dependency(branch2);
  534. assert(!a.merge(b).valid, "Shouldn't be able to merge to different branches");
  535. b = a.merge(a);
  536. assert(b.valid, "Should be able to merge the same branches. (?)");
  537. assert(a == b);
  538.  
  539. a = Dependency(branch1);
  540. assert(a.matches(branch1), "Dependency(branch1) does not match 'branch1'");
  541. assert(a.matches(Version(branch1)), "Dependency(branch1) does not match Version('branch1')");
  542. assert(!a.matches(Version.masterBranch), "Dependency(branch1) matches Version.masterBranch");
  543. assert(!a.matches(branch2), "Dependency(branch1) matches 'branch2'");
  544. assert(!a.matches(Version("1.0.0")), "Dependency(branch1) matches '1.0.0'");
  545. a = Dependency(">=1.0.0");
  546. assert(!a.matches(Version(branch1)), "Dependency(1.0.0) matches 'branch1'");
  547.  
  548. // Testing optional dependencies.
  549. a = Dependency(">=1.0.0");
  550. assert(!a.optional, "Default is not optional.");
  551. b = a;
  552. assert(!a.merge(b).optional, "Merging two not optional dependencies wrong.");
  553. a.optional = true;
  554. assert(!a.merge(b).optional, "Merging optional with not optional wrong.");
  555. b.optional = true;
  556. assert(a.merge(b).optional, "Merging two optional dependencies wrong.");
  557.  
  558. // SemVer's sub identifiers.
  559. a = Dependency(">=1.0.0-beta");
  560. assert(!a.matches(Version("1.0.0-alpha")), "Failed: match 1.0.0-alpha with >=1.0.0-beta");
  561. assert(a.matches(Version("1.0.0-beta")), "Failed: match 1.0.0-beta with >=1.0.0-beta");
  562. assert(a.matches(Version("1.0.0")), "Failed: match 1.0.0 with >=1.0.0-beta");
  563. assert(a.matches(Version("1.0.0-rc")), "Failed: match 1.0.0-rc with >=1.0.0-beta");
  564.  
  565. // Approximate versions.
  566. a = Dependency("~>3.0");
  567. b = Dependency(">=3.0.0 <4.0.0-0");
  568. assert(a == b, "Testing failed: " ~ a.toString());
  569. assert(a.matches(Version("3.1.146")), "Failed: Match 3.1.146 with ~>0.1.2");
  570. assert(!a.matches(Version("0.2.0")), "Failed: Match 0.2.0 with ~>0.1.2");
  571. assert(!a.matches(Version("4.0.0-beta.1")));
  572. a = Dependency("~>3.0.0");
  573. assert(a == Dependency(">=3.0.0 <3.1.0-0"), "Testing failed: " ~ a.toString());
  574. a = Dependency("~>3.5");
  575. assert(a == Dependency(">=3.5.0 <4.0.0-0"), "Testing failed: " ~ a.toString());
  576. a = Dependency("~>3.5.0");
  577. assert(a == Dependency(">=3.5.0 <3.6.0-0"), "Testing failed: " ~ a.toString());
  578. assert(!Dependency("~>3.0.0").matches(Version("3.1.0-beta")));
  579.  
  580. a = Dependency("^0.1.2");
  581. assert(a == Dependency(">=0.1.2 <0.1.3-0"));
  582. a = Dependency("^1.2.3");
  583. assert(a == Dependency(">=1.2.3 <2.0.0-0"), "Testing failed: " ~ a.toString());
  584. a = Dependency("^1.2");
  585. assert(a == Dependency(">=1.2.0 <2.0.0-0"), "Testing failed: " ~ a.toString());
  586.  
  587. a = Dependency("~>0.1.1");
  588. b = Dependency("==0.1.0");
  589. assert(!a.merge(b).valid);
  590. b = Dependency("==0.1.9999");
  591. assert(a.merge(b).valid);
  592. b = Dependency("==0.2.0");
  593. assert(!a.merge(b).valid);
  594. b = Dependency("==0.2.0-beta.1");
  595. assert(!a.merge(b).valid);
  596.  
  597. a = Dependency("~>1.0.1-beta");
  598. b = Dependency(">=1.0.1-beta <1.1.0-0");
  599. assert(a == b, "Testing failed: " ~ a.toString());
  600. assert(a.matches(Version("1.0.1-beta")));
  601. assert(a.matches(Version("1.0.1-beta.6")));
  602.  
  603. a = Dependency("~d2test");
  604. assert(!a.optional);
  605. assert(a.valid);
  606. assert(a.version_ == Version("~d2test"));
  607.  
  608. a = Dependency("==~d2test");
  609. assert(!a.optional);
  610. assert(a.valid);
  611. assert(a.version_ == Version("~d2test"));
  612.  
  613. a = Dependency.any;
  614. assert(!a.optional);
  615. assert(a.valid);
  616. assertThrown(a.version_);
  617. assert(a.matches(Version.masterBranch));
  618. assert(a.matches(Version("1.0.0")));
  619. assert(a.matches(Version("0.0.1-pre")));
  620. b = Dependency(">=1.0.1");
  621. assert(b == a.merge(b));
  622. assert(b == b.merge(a));
  623. b = Dependency(Version.masterBranch);
  624. assert(a.merge(b) == b);
  625. assert(b.merge(a) == b);
  626.  
  627. a.optional = true;
  628. assert(a.matches(Version.masterBranch));
  629. assert(a.matches(Version("1.0.0")));
  630. assert(a.matches(Version("0.0.1-pre")));
  631. b = Dependency(">=1.0.1");
  632. assert(b == a.merge(b));
  633. assert(b == b.merge(a));
  634. b = Dependency(Version.masterBranch);
  635. assert(a.merge(b) == b);
  636. assert(b.merge(a) == b);
  637.  
  638. assert(Dependency("1.0.0").matches(Version("1.0.0+foo")));
  639. assert(Dependency("1.0.0").matches(Version("1.0.0+foo"), VersionMatchMode.standard));
  640. assert(!Dependency("1.0.0").matches(Version("1.0.0+foo"), VersionMatchMode.strict));
  641. assert(Dependency("1.0.0+foo").matches(Version("1.0.0+foo"), VersionMatchMode.strict));
  642. assert(Dependency("~>1.0.0+foo").matches(Version("1.0.0+foo"), VersionMatchMode.strict));
  643. assert(Dependency("~>1.0.0").matches(Version("1.0.0+foo"), VersionMatchMode.strict));
  644.  
  645. logDebug("Dependency unittest success.");
  646. }
  647.  
  648. unittest {
  649. assert(VersionRange.fromString("~>1.0.4").toString() == "~>1.0.4");
  650. assert(VersionRange.fromString("~>1.4").toString() == "~>1.4");
  651. assert(VersionRange.fromString("~>2").toString() == "~>2");
  652. assert(VersionRange.fromString("~>1.0.4+1.2.3").toString() == "~>1.0.4");
  653. assert(VersionRange.fromString("^0.1.2").toString() == "^0.1.2");
  654. assert(VersionRange.fromString("^1.2.3").toString() == "^1.2.3");
  655. assert(VersionRange.fromString("^1.2").toString() == "~>1.2"); // equivalent; prefer ~>
  656. }
  657.  
  658. /**
  659. Represents an SCM repository.
  660. */
  661. struct Repository
  662. {
  663. private string m_remote;
  664. private string m_ref;
  665.  
  666. private Kind m_kind;
  667.  
  668. enum Kind
  669. {
  670. git,
  671. }
  672.  
  673. /**
  674. Params:
  675. remote = Repository remote.
  676. ref_ = Reference to use (SHA1, tag, branch name...)
  677. */
  678. this(string remote, string ref_)
  679. {
  680. enforce(remote.startsWith("git+"), "Unsupported repository type (supports: git+URL)");
  681.  
  682. m_remote = remote["git+".length .. $];
  683. m_kind = Kind.git;
  684. m_ref = ref_;
  685. assert(m_remote.length);
  686. assert(m_ref.length);
  687. }
  688.  
  689. /// Ditto
  690. deprecated("Use the constructor accepting a second parameter named `ref_`")
  691. this(string remote)
  692. {
  693. enforce(remote.startsWith("git+"), "Unsupported repository type (supports: git+URL)");
  694.  
  695. m_remote = remote["git+".length .. $];
  696. m_kind = Kind.git;
  697. assert(m_remote.length);
  698. }
  699.  
  700. string toString() const nothrow pure @safe
  701. {
  702. if (empty) return null;
  703. string kindRepresentation;
  704.  
  705. final switch (kind)
  706. {
  707. case Kind.git:
  708. kindRepresentation = "git";
  709. }
  710. return kindRepresentation~"+"~remote;
  711. }
  712.  
  713. /**
  714. Returns:
  715. Repository URL or path.
  716. */
  717. @property string remote() const @nogc nothrow pure @safe
  718. in { assert(m_remote !is null); }
  719. do
  720. {
  721. return m_remote;
  722. }
  723.  
  724. /**
  725. Returns:
  726. The reference (commit hash, branch name, tag) we are targeting
  727. */
  728. @property string ref_() const @nogc nothrow pure @safe
  729. in { assert(m_remote !is null); }
  730. in { assert(m_ref !is null); }
  731. do
  732. {
  733. return m_ref;
  734. }
  735.  
  736. /**
  737. Returns:
  738. Repository type.
  739. */
  740. @property Kind kind() const @nogc nothrow pure @safe
  741. {
  742. return m_kind;
  743. }
  744.  
  745. /**
  746. Returns:
  747. Whether the repository was initialized with an URL or path.
  748. */
  749. @property bool empty() const @nogc nothrow pure @safe
  750. {
  751. return m_remote.empty;
  752. }
  753. }
  754.  
  755.  
  756. /**
  757. Represents a version in semantic version format, or a branch identifier.
  758.  
  759. This can either have the form "~master", where "master" is a branch name,
  760. or the form "major.update.bugfix-prerelease+buildmetadata" (see the
  761. Semantic Versioning Specification v2.0.0 at http://semver.org/).
  762. */
  763. struct Version {
  764. private {
  765. static immutable MAX_VERS = "99999.0.0";
  766. static immutable UNKNOWN_VERS = "unknown";
  767. static immutable masterString = "~master";
  768. enum branchPrefix = '~';
  769. string m_version;
  770. }
  771.  
  772. static immutable Version minRelease = Version("0.0.0");
  773. static immutable Version maxRelease = Version(MAX_VERS);
  774. static immutable Version masterBranch = Version(masterString);
  775. static immutable Version unknown = Version(UNKNOWN_VERS);
  776.  
  777. /** Constructs a new `Version` from its string representation.
  778. */
  779. this(string vers) @safe pure
  780. {
  781. enforce(vers.length > 1, "Version strings must not be empty.");
  782. if (vers[0] != branchPrefix && vers.ptr !is UNKNOWN_VERS.ptr)
  783. enforce(vers.isValidVersion(), "Invalid SemVer format: " ~ vers);
  784. m_version = vers;
  785. }
  786.  
  787. /** Constructs a new `Version` from its string representation.
  788.  
  789. This method is equivalent to calling the constructor and is used as an
  790. endpoint for the serialization framework.
  791. */
  792. static Version fromString(string vers) @safe pure { return Version(vers); }
  793.  
  794. bool opEquals(in Version oth) const scope @safe pure
  795. {
  796. return opCmp(oth) == 0;
  797. }
  798.  
  799. /// Tests if this represents a branch instead of a version.
  800. @property bool isBranch() const scope @safe pure nothrow @nogc
  801. {
  802. return m_version.length > 0 && m_version[0] == branchPrefix;
  803. }
  804.  
  805. /// Tests if this represents the master branch "~master".
  806. @property bool isMaster() const scope @safe pure nothrow @nogc
  807. {
  808. return m_version == masterString;
  809. }
  810.  
  811. /** Tests if this represents a pre-release version.
  812.  
  813. Note that branches are always considered pre-release versions.
  814. */
  815. @property bool isPreRelease() const scope @safe pure nothrow @nogc
  816. {
  817. if (isBranch) return true;
  818. return isPreReleaseVersion(m_version);
  819. }
  820.  
  821. /// Tests if this represents the special unknown version constant.
  822. @property bool isUnknown() const scope @safe pure nothrow @nogc
  823. {
  824. return m_version == UNKNOWN_VERS;
  825. }
  826.  
  827. /** Tests two versions for equality, according to the selected match mode.
  828. */
  829. bool matches(in Version other, VersionMatchMode mode = VersionMatchMode.standard)
  830. const scope @safe pure
  831. {
  832. if (mode == VersionMatchMode.strict)
  833. return this.toString() == other.toString();
  834. return this == other;
  835. }
  836.  
  837. /** Compares two versions/branches for precedence.
  838.  
  839. Versions generally have precedence over branches and the master branch
  840. has precedence over other branches. Apart from that, versions are
  841. compared using SemVer semantics, while branches are compared
  842. lexicographically.
  843. */
  844. int opCmp(in Version other) const scope @safe pure
  845. {
  846. if (isUnknown || other.isUnknown) {
  847. throw new Exception("Can't compare unknown versions! (this: %s, other: %s)".format(this, other));
  848. }
  849.  
  850. if (isBranch || other.isBranch) {
  851. if(m_version == other.m_version) return 0;
  852. if (!isBranch) return 1;
  853. else if (!other.isBranch) return -1;
  854. if (isMaster) return 1;
  855. else if (other.isMaster) return -1;
  856. return this.m_version < other.m_version ? -1 : 1;
  857. }
  858.  
  859. return compareVersions(m_version, other.m_version);
  860. }
  861.  
  862. /// Returns the string representation of the version/branch.
  863. string toString() const return scope @safe pure nothrow @nogc
  864. {
  865. return m_version;
  866. }
  867. }
  868.  
  869. /**
  870. * A range of versions that are acceptable
  871. *
  872. * While not directly described in SemVer v2.0.0, a common set
  873. * of range operators have appeared among package managers.
  874. * We mostly NPM's: https://semver.npmjs.com/
  875. *
  876. * Hence the acceptable forms for this string are as follows:
  877. *
  878. * $(UL
  879. * $(LI `"1.0.0"` - a single version in SemVer format)
  880. * $(LI `"==1.0.0"` - alternative single version notation)
  881. * $(LI `">1.0.0"` - version range with a single bound)
  882. * $(LI `">1.0.0 <2.0.0"` - version range with two bounds)
  883. * $(LI `"~>1.0.0"` - a fuzzy version range)
  884. * $(LI `"~>1.0"` - a fuzzy version range with partial version)
  885. * $(LI `"^1.0.0"` - semver compatible version range (same version if 0.x.y, ==major >=minor.patch if x.y.z))
  886. * $(LI `"^1.0"` - same as ^1.0.0)
  887. * $(LI `"~master"` - a branch name)
  888. * $(LI `"*" - match any version (see also `VersionRange.Any`))
  889. * )
  890. *
  891. * Apart from "$(LT)" and "$(GT)", "$(GT)=" and "$(LT)=" are also valid
  892. * comparators.
  893. */
  894. public struct VersionRange
  895. {
  896. private Version m_versA;
  897. private Version m_versB;
  898. private bool m_inclusiveA = true; // A comparison > (true) or >= (false)
  899. private bool m_inclusiveB = true; // B comparison < (true) or <= (false)
  900.  
  901. /// Matches any version
  902. public static immutable Any = VersionRange(Version.minRelease, Version.maxRelease);
  903. /// Doesn't match any version
  904. public static immutable Invalid = VersionRange(Version.maxRelease, Version.minRelease);
  905.  
  906. ///
  907. public int opCmp (in VersionRange o) const scope @safe
  908. {
  909. if (m_inclusiveA != o.m_inclusiveA) return m_inclusiveA < o.m_inclusiveA ? -1 : 1;
  910. if (m_inclusiveB != o.m_inclusiveB) return m_inclusiveB < o.m_inclusiveB ? -1 : 1;
  911. if (m_versA != o.m_versA) return m_versA < o.m_versA ? -1 : 1;
  912. if (m_versB != o.m_versB) return m_versB < o.m_versB ? -1 : 1;
  913. return 0;
  914. }
  915.  
  916. public bool matches (in Version v, VersionMatchMode mode = VersionMatchMode.standard)
  917. const @safe
  918. {
  919. if (m_versA.isBranch) {
  920. enforce(this.isExactVersion());
  921. return m_versA == v;
  922. }
  923.  
  924. if (v.isBranch)
  925. return m_versA == v;
  926.  
  927. if (m_versA == m_versB)
  928. return this.m_versA.matches(v, mode);
  929.  
  930. return doCmp(m_inclusiveA, m_versA, v) &&
  931. doCmp(m_inclusiveB, v, m_versB);
  932. }
  933.  
  934. /// Modify in place
  935. public void merge (const VersionRange o) @safe
  936. {
  937. int acmp = m_versA.opCmp(o.m_versA);
  938. int bcmp = m_versB.opCmp(o.m_versB);
  939.  
  940. this.m_inclusiveA = !m_inclusiveA && acmp >= 0 ? false : o.m_inclusiveA;
  941. this.m_versA = acmp > 0 ? m_versA : o.m_versA;
  942. this.m_inclusiveB = !m_inclusiveB && bcmp <= 0 ? false : o.m_inclusiveB;
  943. this.m_versB = bcmp < 0 ? m_versB : o.m_versB;
  944. }
  945.  
  946. /// Returns true $(I iff) the version range only matches a specific version.
  947. @property bool isExactVersion() const scope @safe
  948. {
  949. return this.m_versA == this.m_versB;
  950. }
  951.  
  952. /// Determines if this dependency specification matches arbitrary versions.
  953. /// This is true in particular for the `any` constant.
  954. public bool matchesAny() const scope @safe
  955. {
  956. return this.m_inclusiveA && this.m_inclusiveB
  957. && this.m_versA == Version.minRelease
  958. && this.m_versB == Version.maxRelease;
  959. }
  960.  
  961. unittest {
  962. assert(VersionRange.fromString("*").matchesAny);
  963. assert(!VersionRange.fromString(">0.0.0").matchesAny);
  964. assert(!VersionRange.fromString(">=1.0.0").matchesAny);
  965. assert(!VersionRange.fromString("<1.0.0").matchesAny);
  966. }
  967.  
  968. public static VersionRange fromString (string ves) @safe
  969. {
  970. static import std.string;
  971.  
  972. enforce(ves.length > 0);
  973.  
  974. if (ves == Dependency.ANY_IDENT) {
  975. // Any version is good.
  976. ves = ">=0.0.0";
  977. }
  978.  
  979. if (ves.startsWith("~>")) {
  980. // Shortcut: "~>x.y.z" variant. Last non-zero number will indicate
  981. // the base for this so something like this: ">=x.y.z <x.(y+1).z"
  982. ves = ves[2..$];
  983. return VersionRange(
  984. Version(expandVersion(ves)), Version(bumpVersion(ves) ~ "-0"),
  985. true, false);
  986. }
  987.  
  988. if (ves.startsWith("^")) {
  989. // Shortcut: "^x.y.z" variant. "Semver compatible" - no breaking changes.
  990. // if 0.x.y, ==0.x.y
  991. // if x.y.z, >=x.y.z <(x+1).0.0-0
  992. // ^x.y is equivalent to ^x.y.0.
  993. ves = ves[1..$].expandVersion;
  994. return VersionRange(
  995. Version(ves), Version(bumpIncompatibleVersion(ves) ~ "-0"),
  996. true, false);
  997. }
  998.  
  999. if (ves[0] == Version.branchPrefix) {
  1000. auto ver = Version(ves);
  1001. return VersionRange(ver, ver, true, true);
  1002. }
  1003.  
  1004. if (std.string.indexOf("><=", ves[0]) == -1) {
  1005. auto ver = Version(ves);
  1006. return VersionRange(ver, ver, true, true);
  1007. }
  1008.  
  1009. auto cmpa = skipComp(ves);
  1010. size_t idx2 = std.string.indexOf(ves, " ");
  1011. if (idx2 == -1) {
  1012. if (cmpa == "<=" || cmpa == "<")
  1013. return VersionRange(Version.minRelease, Version(ves), true, (cmpa == "<="));
  1014.  
  1015. if (cmpa == ">=" || cmpa == ">")
  1016. return VersionRange(Version(ves), Version.maxRelease, (cmpa == ">="), true);
  1017.  
  1018. // Converts "==" to ">=a&&<=a", which makes merging easier
  1019. return VersionRange(Version(ves), Version(ves), true, true);
  1020. }
  1021.  
  1022. enforce(cmpa == ">" || cmpa == ">=",
  1023. "First comparison operator expected to be either > or >=, not " ~ cmpa);
  1024. assert(ves[idx2] == ' ');
  1025. VersionRange ret;
  1026. ret.m_versA = Version(ves[0..idx2]);
  1027. ret.m_inclusiveA = cmpa == ">=";
  1028. string v2 = ves[idx2+1..$];
  1029. auto cmpb = skipComp(v2);
  1030. enforce(cmpb == "<" || cmpb == "<=",
  1031. "Second comparison operator expected to be either < or <=, not " ~ cmpb);
  1032. ret.m_versB = Version(v2);
  1033. ret.m_inclusiveB = cmpb == "<=";
  1034.  
  1035. enforce(!ret.m_versA.isBranch && !ret.m_versB.isBranch,
  1036. format("Cannot compare branches: %s", ves));
  1037. enforce(ret.m_versA <= ret.m_versB,
  1038. "First version must not be greater than the second one.");
  1039.  
  1040. return ret;
  1041. }
  1042.  
  1043. /// Returns a string representation of this range
  1044. string toString() const @safe {
  1045. static import std.string;
  1046.  
  1047. string r;
  1048.  
  1049. if (this == Invalid) return "invalid";
  1050. if (this.isExactVersion() && m_inclusiveA && m_inclusiveB) {
  1051. // Special "==" case
  1052. if (m_versA == Version.masterBranch) return "~master";
  1053. else return m_versA.toString();
  1054. }
  1055.  
  1056. // "~>", "^" case
  1057. if (m_inclusiveA && !m_inclusiveB && !m_versA.isBranch) {
  1058. auto vs = m_versA.toString();
  1059. auto i1 = std.string.indexOf(vs, '-'), i2 = std.string.indexOf(vs, '+');
  1060. auto i12 = i1 >= 0 ? i2 >= 0 ? i1 < i2 ? i1 : i2 : i1 : i2;
  1061. auto va = i12 >= 0 ? vs[0 .. i12] : vs;
  1062. auto parts = va.splitter('.').array;
  1063. assert(parts.length == 3, "Version string with a digit group count != 3: "~va);
  1064.  
  1065. foreach (i; 0 .. 3) {
  1066. auto vp = parts[0 .. i+1].join(".");
  1067. auto ve = Version(expandVersion(vp));
  1068. auto veb = Version(bumpVersion(vp) ~ "-0");
  1069. if (ve == m_versA && veb == m_versB) return "~>" ~ vp;
  1070.  
  1071. auto veb2 = Version(bumpIncompatibleVersion(expandVersion(vp)) ~ "-0");
  1072. if (ve == m_versA && veb2 == m_versB) return "^" ~ vp;
  1073. }
  1074. }
  1075.  
  1076. if (m_versA != Version.minRelease) r = (m_inclusiveA ? ">=" : ">") ~ m_versA.toString();
  1077. if (m_versB != Version.maxRelease) r ~= (r.length==0 ? "" : " ") ~ (m_inclusiveB ? "<=" : "<") ~ m_versB.toString();
  1078. if (this.matchesAny()) r = ">=0.0.0";
  1079. return r;
  1080. }
  1081.  
  1082. public bool isValid() const @safe {
  1083. return m_versA <= m_versB && doCmp(m_inclusiveA && m_inclusiveB, m_versA, m_versB);
  1084. }
  1085.  
  1086. private static bool doCmp(bool inclusive, in Version a, in Version b)
  1087. @safe
  1088. {
  1089. return inclusive ? a <= b : a < b;
  1090. }
  1091.  
  1092. private static bool isDigit(char ch) @safe { return ch >= '0' && ch <= '9'; }
  1093. private static string skipComp(ref string c) @safe {
  1094. size_t idx = 0;
  1095. while (idx < c.length && !isDigit(c[idx]) && c[idx] != Version.branchPrefix) idx++;
  1096. enforce(idx < c.length, "Expected version number in version spec: "~c);
  1097. string cmp = idx==c.length-1||idx==0? ">=" : c[0..idx];
  1098. c = c[idx..$];
  1099. switch(cmp) {
  1100. default: enforce(false, "No/Unknown comparison specified: '"~cmp~"'"); return ">=";
  1101. case ">=": goto case; case ">": goto case;
  1102. case "<=": goto case; case "<": goto case;
  1103. case "==": return cmp;
  1104. }
  1105. }
  1106. }
  1107.  
  1108. enum VersionMatchMode {
  1109. standard, /// Match according to SemVer rules
  1110. strict /// Also include build metadata suffix in the comparison
  1111. }
  1112.  
  1113. unittest {
  1114. Version a, b;
  1115.  
  1116. assertNotThrown(a = Version("1.0.0"), "Constructing Version('1.0.0') failed");
  1117. assert(!a.isBranch, "Error: '1.0.0' treated as branch");
  1118. assert(a == a, "a == a failed");
  1119.  
  1120. assertNotThrown(a = Version(Version.masterString), "Constructing Version("~Version.masterString~"') failed");
  1121. assert(a.isBranch, "Error: '"~Version.masterString~"' treated as branch");
  1122. assert(a.isMaster);
  1123. assert(a == Version.masterBranch, "Constructed master version != default master version.");
  1124.  
  1125. assertNotThrown(a = Version("~BRANCH"), "Construction of branch Version failed.");
  1126. assert(a.isBranch, "Error: '~BRANCH' not treated as branch'");
  1127. assert(!a.isMaster);
  1128. assert(a == a, "a == a with branch failed");
  1129.  
  1130. // opCmp
  1131. a = Version("1.0.0");
  1132. b = Version("1.0.0");
  1133. assert(a == b, "a == b with a:'1.0.0', b:'1.0.0' failed");
  1134. b = Version("2.0.0");
  1135. assert(a != b, "a != b with a:'1.0.0', b:'2.0.0' failed");
  1136.  
  1137. a = Version.masterBranch;
  1138. b = Version("~BRANCH");
  1139. assert(a != b, "a != b with a:MASTER, b:'~branch' failed");
  1140. assert(a > b);
  1141. assert(a < Version("0.0.0"));
  1142. assert(b < Version("0.0.0"));
  1143. assert(a > Version("~Z"));
  1144. assert(b < Version("~Z"));
  1145.  
  1146. // SemVer 2.0.0-rc.2
  1147. a = Version("2.0.0-rc.2");
  1148. b = Version("2.0.0-rc.3");
  1149. assert(a < b, "Failed: 2.0.0-rc.2 < 2.0.0-rc.3");
  1150.  
  1151. a = Version("2.0.0-rc.2+build-metadata");
  1152. b = Version("2.0.0+build-metadata");
  1153. assert(a < b, "Failed: "~a.toString()~"<"~b.toString());
  1154.  
  1155. // 1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0
  1156. Version[] versions;
  1157. versions ~= Version("1.0.0-alpha");
  1158. versions ~= Version("1.0.0-alpha.1");
  1159. versions ~= Version("1.0.0-beta.2");
  1160. versions ~= Version("1.0.0-beta.11");
  1161. versions ~= Version("1.0.0-rc.1");
  1162. versions ~= Version("1.0.0");
  1163. for(int i=1; i<versions.length; ++i)
  1164. for(int j=i-1; j>=0; --j)
  1165. assert(versions[j] < versions[i], "Failed: " ~ versions[j].toString() ~ "<" ~ versions[i].toString());
  1166.  
  1167. a = Version.unknown;
  1168. b = Version.minRelease;
  1169. assertThrown(a == b, "Failed: compared " ~ a.toString() ~ " with " ~ b.toString() ~ "");
  1170.  
  1171. a = Version.unknown;
  1172. b = Version.unknown;
  1173. assertThrown(a == b, "Failed: UNKNOWN == UNKNOWN");
  1174.  
  1175. assert(Version("1.0.0+a") == Version("1.0.0+b"));
  1176.  
  1177. assert(Version("1.0.0").matches(Version("1.0.0+foo")));
  1178. assert(Version("1.0.0").matches(Version("1.0.0+foo"), VersionMatchMode.standard));
  1179. assert(!Version("1.0.0").matches(Version("1.0.0+foo"), VersionMatchMode.strict));
  1180. assert(Version("1.0.0+foo").matches(Version("1.0.0+foo"), VersionMatchMode.strict));
  1181. }
  1182.  
  1183. /// Determines whether the given string is a Git hash.
  1184. bool isGitHash(string hash) @nogc nothrow pure @safe
  1185. {
  1186. import std.ascii : isHexDigit;
  1187. import std.utf : byCodeUnit;
  1188.  
  1189. return hash.length >= 7 && hash.length <= 40 && hash.byCodeUnit.all!isHexDigit;
  1190. }
  1191.  
  1192. @nogc nothrow pure @safe unittest {
  1193. assert(isGitHash("73535568b79a0b124bc1653002637a830ce0fcb8"));
  1194. assert(!isGitHash("735"));
  1195. assert(!isGitHash("73535568b79a0b124bc1-53002637a830ce0fcb8"));
  1196. assert(!isGitHash("73535568b79a0b124bg1"));
  1197. }