-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathutils.js
More file actions
42 lines (34 loc) · 1.49 KB
/
utils.js
File metadata and controls
42 lines (34 loc) · 1.49 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
/**
* Utility Methods
*
* Credit: Kent C. Dodds
*
* @see https://github.com/kentcdodds/kcd-scripts/blob/main/src/utils.js
*/
import fs from 'node:fs';
import { cosmiconfigSync } from 'cosmiconfig';
import has from 'lodash.has';
import { readPackageUpSync } from 'read-package-up';
const { packageJson: pkg, path: pkgPath } = readPackageUpSync({ cwd: fs.realpathSync(process.cwd()) }) || {};
const hasPkgProp = props => [props].flat().some(prop => has(pkg, prop));
const hasPkgSubProp = pkgProp => props => hasPkgProp([props].flat().map(p => `${pkgProp}.${p}`));
export const hasDep = hasPkgSubProp('dependencies');
export const hasDevDep = hasPkgSubProp('devDependencies');
export const hasPeerDep = hasPkgSubProp('peerDependencies');
export const hasAnyDep = args => [hasDep, hasDevDep, hasPeerDep].some(fn => fn(args));
export const ifAnyDep = (deps, t, f) => (hasAnyDep([deps].flat()) ? t : f);
/**
* Get the version of a dependency from the consumer's package.json.
* Returns the major version as a string (e.g. '18', '19'), or null if not found.
*/
export function getDepVersion(dep) {
const spec = pkg?.dependencies?.[dep] || pkg?.devDependencies?.[dep] || pkg?.peerDependencies?.[dep];
if (!spec) return null;
const match = spec.match(/\d+/);
return match ? match[0] : null;
}
export function hasLocalConfig(moduleName, searchOptions = {}) {
const explorerSync = cosmiconfigSync(moduleName, searchOptions);
const result = explorerSync.search(pkgPath || './');
return result !== null;
}