all files / lib/ json.js

96.43% Statements 27/28
85.71% Branches 12/14
100% Functions 4/4
95% Lines 19/20
1 branch Ignored     
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                                     25×   25× 25× 25×     25×   25×       25× 75×   823× 75×         25×  
import path from 'path';
import fs from 'fs-extra';
import each from 'lodash/each';
 
const packageJson = 'package.json';
 
const packageKeys = [
  'dependencies',
  'devDependencies',
  'peerDependencies'
];
 
/**
 * RegExp used to find yarn packages.
 * @type {RegExp}
 */
export const yarnPackageNameRegex = /^yarn\-/;
 
/**
 * Looks at a package.json file and retrieves all module names that pass our
 * yarnPackageNameRegex, effectively all packages that start with `yarn-`.
 * @param {string} directory Directory to look for a package.json file.
 * @return {Array} Array of package names found.
 */
export function getYarnPackageNames(directory = '') {
  const packagePath = path.join(directory, packageJson);
 
  let json;
  try {
    json = fs.readJsonSync(packagePath);
  } catch (e) { /* swallow */ }
 
  let moduleNames = [];
 
  Iif (!json) {
    return moduleNames;
  }
 
  packageKeys.forEach(packageKey => {
    each(json[packageKey], (version, name) => {
      // Only include a yarn package extension once.
      if (yarnPackageNameRegex.test(name) && !moduleNames.includes(name)) {
        moduleNames.push(name);
      }
    });
  });
 
  return moduleNames;
}