min-version.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. const SemVer = require('../classes/semver')
  2. const Range = require('../classes/range')
  3. const gt = require('../functions/gt')
  4. const minVersion = (range, loose) => {
  5. range = new Range(range, loose)
  6. let minver = new SemVer('0.0.0')
  7. if (range.test(minver)) {
  8. return minver
  9. }
  10. minver = new SemVer('0.0.0-0')
  11. if (range.test(minver)) {
  12. return minver
  13. }
  14. minver = null
  15. for (let i = 0; i < range.set.length; ++i) {
  16. const comparators = range.set[i]
  17. let setMin = null
  18. comparators.forEach((comparator) => {
  19. // Clone to avoid manipulating the comparator's semver object.
  20. const compver = new SemVer(comparator.semver.version)
  21. switch (comparator.operator) {
  22. case '>':
  23. if (compver.prerelease.length === 0) {
  24. compver.patch++
  25. } else {
  26. compver.prerelease.push(0)
  27. }
  28. compver.raw = compver.format()
  29. /* fallthrough */
  30. case '':
  31. case '>=':
  32. if (!setMin || gt(compver, setMin)) {
  33. setMin = compver
  34. }
  35. break
  36. case '<':
  37. case '<=':
  38. /* Ignore maximum versions */
  39. break
  40. /* istanbul ignore next */
  41. default:
  42. throw new Error(`Unexpected operation: ${comparator.operator}`)
  43. }
  44. })
  45. if (setMin && (!minver || gt(minver, setMin)))
  46. minver = setMin
  47. }
  48. if (minver && range.test(minver)) {
  49. return minver
  50. }
  51. return null
  52. }
  53. module.exports = minVersion