no-empty-file.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. const MESSAGE_ID = 'no-empty-file';
  3. const messages = {
  4. [MESSAGE_ID]: 'Empty files are not allowed.',
  5. };
  6. const isEmpty = node =>
  7. (
  8. (node.type === 'Program' || node.type === 'BlockStatement')
  9. && node.body.every(currentNode => isEmpty(currentNode))
  10. )
  11. || node.type === 'EmptyStatement'
  12. || (node.type === 'ExpressionStatement' && 'directive' in node);
  13. const isTripleSlashDirective = node =>
  14. node.type === 'Line' && node.value.startsWith('/');
  15. const hasTripeSlashDirectives = comments =>
  16. comments.some(currentNode => isTripleSlashDirective(currentNode));
  17. /** @param {import('eslint').Rule.RuleContext} context */
  18. const create = context => {
  19. const filename = context.getPhysicalFilename().toLowerCase();
  20. if (!/\.(?:js|mjs|cjs|ts|mts|cts)$/.test(filename)) {
  21. return {};
  22. }
  23. return {
  24. Program(node) {
  25. if (!isEmpty(node)) {
  26. return;
  27. }
  28. const sourceCode = context.getSourceCode();
  29. const comments = sourceCode.getAllComments();
  30. if (hasTripeSlashDirectives(comments)) {
  31. return;
  32. }
  33. return {
  34. node,
  35. messageId: MESSAGE_ID,
  36. };
  37. },
  38. };
  39. };
  40. /** @type {import('eslint').Rule.RuleModule} */
  41. module.exports = {
  42. create,
  43. meta: {
  44. type: 'suggestion',
  45. docs: {
  46. description: 'Disallow empty files.',
  47. },
  48. schema: [],
  49. messages,
  50. },
  51. };