How to use the parse function from semver

Find comprehensive JavaScript semver.parse code examples handpicked from public code repositorys.

The semver.parse function is used to parse a version string in semver format into its constituent parts.

75
76
77
78
79
80
81
82
83
84
85
86
var getTaggedVersion = function() {
  var gitTagResult = shell.exec('git describe --exact-match', {silent:true});


  if ( gitTagResult.code === 0 ) {
    var tag = gitTagResult.output.trim();
    var version = semver.parse(tag);


    if ( version && semver.satisfies(version, currentPackage.branchVersion)) {
      version.codeName = getCodeName(tag);
      version.full = version.version;
fork icon1
star icon2
watch icon4

+ 9 other calls in file

196
197
198
199
200
201
202
203
204
205
let v = version.slice(indexOfGtEq + 2)
const indexOfLt = v.indexOf('<')
if (indexOfLt >= 0) {
  v = v.slice(0, indexOfLt)
}
const found = semver.parse(v, { loose: true, includePrerelease: true })

if (found && found.version) {
  return found.version
}
fork icon0
star icon2
watch icon43

+ 3 other calls in file

How does semver.parse work?

The semver.parse function is a part of the semver package, and it is used to parse a version string in semver format into its constituent parts. To accomplish this, the function accepts a single argument, which is the version string to be parsed. If the version string is in semver format, the function returns an object that contains the following properties: major: the major version number minor: the minor version number patch: the patch version number prerelease: an array of prerelease identifiers, if any build: an array of build identifiers, if any If the version string is not in semver format, the function returns null. By using the semver.parse function, developers can programmatically parse a version string into its constituent parts, which can be useful in scenarios where they need to compare or manipulate versions. This can include tasks such as checking if a version is within a certain range, finding the latest version of a package, or comparing the versions of two dependencies to see if they are compatible.

5
6
7
8
9
10
11
12
13
14
15
 * Output version details
 * @param {string} version version number
 * @param {string} bump version bump name (major, minor, patch)
 */
const setVersionOutputs = (version, bump) => {
  const output = semver.parse(version)


  core.setOutput('version', output.version)
  core.setOutput('version-with-prefix', `v${output.version}`)
  core.setOutput('major', output.major)
fork icon1
star icon0
watch icon1

330
331
332
333
334
335
336
337
338
339
const versionDiff = semver.diff(info.installed.version, version);
if (versionDiff !== 'patch' &&
    versionDiff !== 'minor' &&
    /^@(?:angular|nguniversal)\//.test(name)) {
    const installedMajorVersion = (_a = semver.parse(info.installed.version)) === null || _a === void 0 ? void 0 : _a.major;
    const toInstallMajorVersion = (_b = semver.parse(version)) === null || _b === void 0 ? void 0 : _b.major;
    if (installedMajorVersion !== undefined &&
        toInstallMajorVersion !== undefined &&
        installedMajorVersion < toInstallMajorVersion - 1) {
        const nextMajorVersion = `${installedMajorVersion + 1}.`;
fork icon1
star icon0
watch icon0

+ 2 other calls in file

Ai Example

1
2
3
4
5
6
7
const semver = require("semver");

const versionString = "1.2.3-beta.4+build.5";

const version = semver.parse(versionString);

console.log(version);

In this example, we're using semver.parse to parse the versionString variable into its constituent parts. We call semver.parse with the versionString variable as its argument, and we store the result in a version variable. We log the version variable to the console to see its constituent parts. The console output will be: yaml Copy code

1
2
3
4
5
6
7
8
9
10
11


var path = require('path')
var url = require('url')
var Stream = require('stream').Stream
var semver = require('semver')
var stableFamily = semver.parse(process.version)
var nopt = require('nopt')
var os = require('os')
var osenv = require('osenv')
var umask = require('../utils/umask')
fork icon0
star icon1
watch icon1

+ 5 other calls in file

8
9
10
11
12
13
14
15
16
17
18
19


/////////////////////////////////////////////
//========= Check node.js version =========//
/////////////////////////////////////////////


// const nodeVersion = semver.parse(process.version);
// if (nodeVersion.major < 13) {
//     logger(`Your Node.js ${process.version} is not supported, it required Node.js 13 to run bot!`, "error");
//     return process.exit(0);
// };
fork icon1
star icon0
watch icon1

22
23
24
25
26
27
28
29
30
31
  return [];
}

const majorVersions = {};
tagResults.stdout.replace(versionMatcher, (_, tag) => {
  const version = semver.parse(tag);

  // Not interested in tags that do not match semver format.
  if (version === null) {
    return;
fork icon0
star icon0
watch icon1

+ 7 other calls in file

57
58
59
60
61
62
63
64
65
66
  throw new Error('get_node_abi requires valid runtime arg');
}
if (!versions) {
  throw new Error('get_node_abi requires valid process.versions object');
}
const sem_ver = semver.parse(versions.node);
if (sem_ver.major === 0 && sem_ver.minor % 2) { // odd series
  // https://github.com/mapbox/node-pre-gyp/issues/124
  return runtime + '-v' + versions.node;
} else {
fork icon0
star icon0
watch icon1

+ 14 other calls in file

180
181
182
183
184
185
186
187
188
189
// If we're currently in a pre-release we need to manually execute the
// patch bump up to the next version. And we also need to make sure we
// resume the releases at the same pre-release tag.
const currentPrerelease = semver.prerelease(pkg.packageJson.version);
if (currentPrerelease) {
  const parsed = semver.parse(targetVersion);
  parsed.inc('patch');
  parsed.prerelease = currentPrerelease;
  targetVersion = parsed.format();
}
fork icon0
star icon0
watch icon1

6
7
8
9
10
11
12
13
14
15
16
17
// get the current package.json version
const { version } = require('./package.json');
const semver = require('semver');


// extract the major (left-most) number
const { major } = semver.parse(version);


module.exports = {
  entry: './src/index.tsx',
  mode: isProduction ? 'production' : 'development',
fork icon0
star icon0
watch icon1

+ 2 other calls in file

57
58
59
60
61
62
63
64
65
66
    throw new Error("get_node_abi requires valid runtime arg");
}
if (!versions) {
    throw new Error("get_node_abi requires valid process.versions object");
}
var sem_ver = semver.parse(versions.node);
if (sem_ver.major === 0 && sem_ver.minor % 2) { // odd series
    // https://github.com/mapbox/node-pre-gyp/issues/124
    return runtime+'-v'+versions.node;
} else {
fork icon0
star icon0
watch icon0

+ 8 other calls in file

251
252
253
254
255
256
257
258
259
260
261
    //这里用来解决UnhandledPromiseRejectionWarning的问题
  });
};


function getVersionWithoutPatch(version) {
  const sVer = semver.parse(version);
  let verWithPatch = sVer.prerelease.length > 0 ? "-" + sVer.prerelease[0] : "";
  verWithPatch = sVer.major + "." + sVer.minor + verWithPatch;
  return verWithPatch;
}
fork icon0
star icon0
watch icon1

28
29
30
31
32
33
34
35
36
37
38
  githubToken,
  oldReleaseNotes
) {
  let oldVersion = null;
  let oldVersionName = null;
  const parsedVersion = semver.parse(releaseVersion);
  const newVersionBranch = getBranchForVersion(parsedVersion);


  if (githubToken) {
    changelog.setGithubAccessToken(githubToken);
fork icon0
star icon0
watch icon1

17
18
19
20
21
22
23
24
25
26
27
28
29


const { execSync } = require('child_process')
const semver = require('semver')
const path = require('path')


const getMajorVersion = (input) => semver.parse(input).major
const getMinorVersion = (input) => semver.parse(input).minor


// INFO: String templates to generate the tags to update
const LATEST_TAG = (strings, major) => `latest-${major}`
fork icon0
star icon0
watch icon0

-4
-3
-2
var semver = require('semver')
var version = semver.parse(require('../package.json').version)
console.log('v%s.%s-next', version.major, version.minor)
fork icon0
star icon0
watch icon0

11
12
13
14
15
16
17
18
19
20

if (version) {
  const {
    minor,
    patch,
  } = semver.parse(version);

  if (patch < maxVersion) {
    manifest.version = semver.inc(version, 'patch');
  } else if (minor < maxVersion) {
fork icon0
star icon0
watch icon0

682
683
684
685
686
687
688
689
690
691
    // migrations for @angular/core@13 can be executed using Angular/cli@13.
    // This is same behaviour as `npx @angular/cli@13 update @angular/core@13`.
    // `@angular/cli@13` -> ['', 'angular/cli', '13']
    // `@angular/cli` -> ['', 'angular/cli']
    const tempVersion = coerceVersionNumber(updatingAngularPackage.split('@')[2]);
    return (_b = (_a = semver.parse(tempVersion)) === null || _a === void 0 ? void 0 : _a.major) !== null && _b !== void 0 ? _b : 'latest';
}
// When not updating an Angular package we cannot determine which schematic runtime the migration should to be executed in.
// Typically, we can assume that the `@angular/cli` was updated previously.
// Example: Angular official packages are typically updated prior to NGRX etc...
fork icon0
star icon0
watch icon0

215
216
217
218
219
220
221
222
223
224
    </td>
  </tr>
`).join('\n')}
  ${[...this.changedPackages].filter(pkg => !excludedPackages.has(pkg) && this.existingPackages.has(pkg)).map(pkg => {
    let json = JSON.parse(fs.readFileSync(`packages/${pkg}/package.json`, 'utf8'));
    let version = semver.parse(json.version);
    return `
      <tr>
        <td><code>${pkg}</code></td>
        <td>
fork icon0
star icon0
watch icon0

+ 3 other calls in file

58
59
60
61
62
63
64
65
66
67
    fileName.endsWith(firmwareString)
  ) {
    const startIndex = title.toLowerCase().length + 1;
    const endIndex = fileName.indexOf("." + firmwareString);
    const version = fileInfo.name.substring(startIndex, endIndex);
    fileInfo.version = semver.parse(version);
    return fileInfo;
  }
});
return firmwareList;
fork icon0
star icon0
watch icon0