-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathgetPkg.ts
More file actions
77 lines (68 loc) · 2.1 KB
/
getPkg.ts
File metadata and controls
77 lines (68 loc) · 2.1 KB
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
68
69
70
71
72
73
74
75
76
77
import type { Hook } from '@oclif/core';
import semver from 'semver';
import pkg from '../../package.json' with { type: 'json' };
import { error } from './logger.js';
const registryUrl = 'https://registry.npmjs.com/rdme';
/**
* @see {@link https://docs.npmjs.com/adding-dist-tags-to-packages}
*/
type npmDistTag = 'latest';
/**
* Return the major Node.js version specified in our `package.json` config.
*
* @example 14
*/
export function getNodeVersion(): string {
const { node } = pkg.engines;
const parsedVersion = semver.minVersion(node);
if (!parsedVersion) {
throw new Error('`version` value in package.json is invalid');
}
return parsedVersion.major.toString();
}
/**
* The current `rdme` version, as specified in the `package.json`
* or in the oclif hook context.
*
* @example "8.0.0"
* @note we mock this function in our snapshots
* @see {@link https://stackoverflow.com/a/54245672}
*/
export function getPkgVersion(this: Hook.Context | void): string {
return this?.config?.version || pkg.version;
}
/**
* The current `rdme` version
*
* @example "8.0.0"
* @see {@link https://docs.npmjs.com/adding-dist-tags-to-packages}
* @note we mock this function in our snapshots
* @see {@link https://stackoverflow.com/a/54245672}
*/
export async function getPkgVersionFromNPM(
this: Hook.Context | void,
/**
* The `npm` dist tag to retrieve. If this value is omitted,
* the version from the `package.json` is returned.
*/
npmDistTag?: npmDistTag,
): Promise<string> {
if (npmDistTag) {
return fetch(registryUrl)
.then(res => res.json() as Promise<{ 'dist-tags': Record<string, string> }>)
.then(body => body['dist-tags'][npmDistTag])
.catch(err => {
error(`error fetching version from npm registry: ${err.message}`);
return getPkgVersion.call(this);
});
}
return getPkgVersion.call(this);
}
/**
* The current major `rdme` version
*
* @example 8
*/
export async function getMajorPkgVersion(this: Hook.Context | void, npmDistTag?: npmDistTag): Promise<number> {
return semver.major(await getPkgVersionFromNPM.call(this, npmDistTag));
}