check-extraneous.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * @author Toru Nagashima
  3. * @copyright 2017 Toru Nagashima. All rights reserved.
  4. * See LICENSE file in root directory for full license.
  5. */
  6. "use strict"
  7. //------------------------------------------------------------------------------
  8. // Requirements
  9. //------------------------------------------------------------------------------
  10. const getAllowModules = require("./get-allow-modules")
  11. const getPackageJson = require("./get-package-json")
  12. //------------------------------------------------------------------------------
  13. // Public Interface
  14. //------------------------------------------------------------------------------
  15. /**
  16. * Checks whether or not each requirement target is published via package.json.
  17. *
  18. * It reads package.json and checks the target exists in `dependencies`.
  19. *
  20. * @param {RuleContext} context - A context to report.
  21. * @param {string} filePath - The current file path.
  22. * @param {ImportTarget[]} targets - A list of target information to check.
  23. * @returns {void}
  24. */
  25. module.exports = function checkForExtraneous(context, filePath, targets) {
  26. const packageInfo = getPackageJson(filePath)
  27. if (!packageInfo) {
  28. return
  29. }
  30. const allowed = new Set(getAllowModules(context))
  31. const dependencies = new Set(
  32. [].concat(
  33. Object.keys(packageInfo.dependencies || {}),
  34. Object.keys(packageInfo.devDependencies || {}),
  35. Object.keys(packageInfo.peerDependencies || {}),
  36. Object.keys(packageInfo.optionalDependencies || {})
  37. )
  38. )
  39. for (const target of targets) {
  40. const extraneous = (
  41. target.moduleName != null &&
  42. target.filePath != null &&
  43. !dependencies.has(target.moduleName) &&
  44. !allowed.has(target.moduleName)
  45. )
  46. if (extraneous) {
  47. context.report({
  48. node: target.node,
  49. loc: target.node.loc,
  50. message: "\"{{moduleName}}\" is extraneous.",
  51. data: target,
  52. })
  53. }
  54. }
  55. }