min-version.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. }
  49. if (minver && range.test(minver)) {
  50. return minver
  51. }
  52. return null
  53. }
  54. module.exports = minVersion