wix-incubator / lerna-script

Lerna addon for adding custom tasks
MIT License
164 stars 13 forks source link

feat: depchecks-fix script #451

Open jeswr opened 2 years ago

jeswr commented 2 years ago

Similar to how there is a depchecks script, I have made the following depchecks-fix script for a project I am working on which I thought might be useful to have upstream.

The idea is that it will go through each module, run yarn add on the missing deps and run yarn remove on any unneeded deps. In my case since all dev dependencies should be listed in the main package.json for the repo; I remove the devDependencies of any packages in the repo.

My current implementation is

const {loadPackages, exec, iter} = require('lerna-script')
const checkDeps = require('depcheck')
const path = require('path');

async function depcheckTask(log) {
  return iter.forEach((await (log.packages || loadPackages())).filter(package => package.location.startsWith(path.join(__dirname, '/packages'))), { log })(async package => {
    const {dependencies, devDependencies, missing, using} = await checkDeps(package.location, { ignorePatterns: [
      // files matching these patterns will be ignored
      'test/*',
    ], }, val => val);

    log.info(package.name)

    const missing_deps = Object.keys(missing)
    if (missing_deps.length > 0) {
      try {
        log.info('    add:', missing_deps.join(', '))
        await exec.command(package)(`yarn add ${missing_deps.join(' ')}`);
      } catch (e) {
        for (const dep of missing_deps) {
          try {
            await exec.command(package)(`yarn add ${dep}`);
          } catch (e) {
            log.error('    CANNOT ADD:', dep);
          }
        }
      }
    }

    const unused_deps = [...dependencies, ...devDependencies].filter(elem => !Object.keys(using).includes(elem));
    if (unused_deps.length > 0) {
      try {
        log.info('    remove:', unused_deps.join(', '))
        await exec.command(package)(`yarn remove ${unused_deps.join(' ')}`);
      } catch (e) {
        for (const dep of unused_deps) {
          try {
            await exec.command(package)(`yarn remove ${dep}`);
          } catch (e) {
            log.error('    CANNOT REMOVE:', dep);
          }
        }
      }
    }
  })
}

module.exports.depcheckTask = depcheckTask