Skip to content

Commit

Permalink
Account for operators when computing range intersections with same ve…
Browse files Browse the repository at this point in the history
…rsion (#53)
  • Loading branch information
adamreeve authored Mar 14, 2022
1 parent 713d3b7 commit ca8b6b7
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
30 changes: 28 additions & 2 deletions src/SemanticVersioning/ComparatorSet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,14 +92,40 @@ public ComparatorSet Intersect(ComparatorSet other)
c.ComparatorType == Comparator.Operator.LessThan ||
c.ComparatorType == Comparator.Operator.LessThanOrEqual ||
c.ComparatorType == Comparator.Operator.LessThanExcludingPrereleases;
// When two comparators have the same version, the one with the more restrictive
// range should take precedence.
Func<Comparator.Operator, int> operatorOrdering = op =>
{
switch (op)
{
case Comparator.Operator.LessThanExcludingPrereleases:
return 0;
case Comparator.Operator.LessThan:
return 1;
case Comparator.Operator.LessThanOrEqual:
return 2;
case Comparator.Operator.GreaterThan:
return 0;
case Comparator.Operator.GreaterThanOrEqual:
return 1;
case Comparator.Operator.GreaterThanOrEqualIncludingPrereleases:
return 2;
default:
throw new ArgumentOutOfRangeException(nameof(op), op, "Unexpected comparator operator");
}
};
var maxOfMins =
_comparators.Concat(other._comparators)
.Where(operatorIsGreaterThan)
.OrderByDescending(c => c.Version).FirstOrDefault();
.OrderByDescending(c => c.Version)
.ThenBy(c => operatorOrdering(c.ComparatorType))
.FirstOrDefault();
var minOfMaxs =
_comparators.Concat(other._comparators)
.Where(operatorIsLessThan)
.OrderBy(c => c.Version).FirstOrDefault();
.OrderBy(c => c.Version)
.ThenBy(c => operatorOrdering(c.ComparatorType))
.FirstOrDefault();
if (maxOfMins != null && minOfMaxs != null && !maxOfMins.Intersects(minOfMaxs))
{
return null;
Expand Down
4 changes: 4 additions & 0 deletions test/SemanticVersioning.Tests/RangeOperations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ public class RangeOperations
[InlineData("~1.2.3 || ~1.3.2", ">=1.2.9 < 1.3.8", "~1.2.9 || >=1.3.2 < 1.3.8")]
[InlineData("<3.0.0", ">=3.0.0", "<0.0.0")]
[InlineData("^2", "^3", "<0.0.0")]
[InlineData(">=1.0.0 <2.0.0", ">1.0.0", ">1.0.0 <2.0.0")]
[InlineData(">1.0.0", ">=1.0.0 <2.0.0", ">1.0.0 <2.0.0")]
[InlineData(">1.0.0 <2.0.0", "<=2.0.0", ">1.0.0 <2.0.0")]
[InlineData("<=2.0.0", ">1.0.0 <2.0.0", ">1.0.0 <2.0.0")]
public void Intersect(string a, string b, string intersect)
{
var rangeA = new Range(a);
Expand Down

0 comments on commit ca8b6b7

Please sign in to comment.