All files / semver / _test_comparator_set.ts

100.00% Branches 23/23
100.00% Lines 56/56
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
 
 
 
x28
x28
 
x1081
x1081
x1107
x1107
x2108
x2108
x1081
x2219
x1138
x1138
x2164
x1083
x1083
x2192
x1111
x1111
x2512
x1431
x1431
x2689
x1608
x1608
x2223
x1142
x1142
x1081
x1081
 
x28
x28
x28
 
x755
x1808
x2169
x2169
x1808
x755
 
 
 
 
 
x779
x814
x815
x815
x848
x814
x827
x827
x827
x827
x837
x837
x827
x814
x793
x793
x1097
x755

































































// Copyright 2018-2025 the Deno authors. MIT license.

import type { Comparator, SemVer } from "./types.ts";
import { isWildcardComparator } from "./_shared.ts";
import { compare } from "./compare.ts";

function testComparator(version: SemVer, comparator: Comparator): boolean {
  if (isWildcardComparator(comparator)) {
    return true;
  }
  const cmp = compare(version, comparator);
  switch (comparator.operator) {
    case "=":
    case undefined: {
      return cmp === 0;
    }
    case "!=": {
      return cmp !== 0;
    }
    case ">": {
      return cmp > 0;
    }
    case "<": {
      return cmp < 0;
    }
    case ">=": {
      return cmp >= 0;
    }
    case "<=": {
      return cmp <= 0;
    }
  }
}

export function testComparatorSet(
  version: SemVer,
  set: Comparator[],
): boolean {
  for (const comparator of set) {
    if (!testComparator(version, comparator)) {
      return false;
    }
  }
  if (version.prerelease && version.prerelease.length > 0) {
    // Find the comparator that is allowed to have prereleases
    // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
    // That should allow `1.2.3-pr.2` to pass.
    // However, `1.2.4-alpha.notready` should NOT be allowed,
    // even though it's within the range set by the comparators.
    for (const comparator of set) {
      if (isWildcardComparator(comparator)) {
        continue;
      }
      const { major, minor, patch, prerelease } = comparator;
      if (prerelease && prerelease.length > 0) {
        if (
          version.major === major && version.minor === minor &&
          version.patch === patch
        ) {
          return true;
        }
      }
    }
    return false;
  }
  return true;
}