filename-case.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. 'use strict';
  2. const path = require('node:path');
  3. const {camelCase, kebabCase, snakeCase, upperFirst} = require('lodash');
  4. const cartesianProductSamples = require('./utils/cartesian-product-samples.js');
  5. const MESSAGE_ID = 'filename-case';
  6. const MESSAGE_ID_EXTENSION = 'filename-extension';
  7. const messages = {
  8. [MESSAGE_ID]: 'Filename is not in {{chosenCases}}. Rename it to {{renamedFilenames}}.',
  9. [MESSAGE_ID_EXTENSION]: 'File extension `{{extension}}` is not in lowercase. Rename it to `{{filename}}`.',
  10. };
  11. const pascalCase = string => upperFirst(camelCase(string));
  12. const numberRegex = /\d+/;
  13. const PLACEHOLDER = '\uFFFF\uFFFF\uFFFF';
  14. const PLACEHOLDER_REGEX = new RegExp(PLACEHOLDER, 'i');
  15. const isIgnoredChar = char => !/^[a-z\d-_]$/i.test(char);
  16. const ignoredByDefault = new Set(['index.js', 'index.mjs', 'index.cjs', 'index.ts', 'index.tsx', 'index.vue']);
  17. const isLowerCase = string => string === string.toLowerCase();
  18. function ignoreNumbers(caseFunction) {
  19. return string => {
  20. const stack = [];
  21. let execResult = numberRegex.exec(string);
  22. while (execResult) {
  23. stack.push(execResult[0]);
  24. string = string.replace(execResult[0], PLACEHOLDER);
  25. execResult = numberRegex.exec(string);
  26. }
  27. let withCase = caseFunction(string);
  28. while (stack.length > 0) {
  29. withCase = withCase.replace(PLACEHOLDER_REGEX, stack.shift());
  30. }
  31. return withCase;
  32. };
  33. }
  34. const cases = {
  35. camelCase: {
  36. fn: camelCase,
  37. name: 'camel case',
  38. },
  39. kebabCase: {
  40. fn: kebabCase,
  41. name: 'kebab case',
  42. },
  43. snakeCase: {
  44. fn: snakeCase,
  45. name: 'snake case',
  46. },
  47. pascalCase: {
  48. fn: pascalCase,
  49. name: 'pascal case',
  50. },
  51. };
  52. /**
  53. Get the cases specified by the option.
  54. @param {object} options
  55. @returns {string[]} The chosen cases.
  56. */
  57. function getChosenCases(options) {
  58. if (options.case) {
  59. return [options.case];
  60. }
  61. if (options.cases) {
  62. const cases = Object.keys(options.cases)
  63. .filter(cases => options.cases[cases]);
  64. return cases.length > 0 ? cases : ['kebabCase'];
  65. }
  66. return ['kebabCase'];
  67. }
  68. function validateFilename(words, caseFunctions) {
  69. return words
  70. .filter(({ignored}) => !ignored)
  71. .every(({word}) => caseFunctions.some(caseFunction => caseFunction(word) === word));
  72. }
  73. function fixFilename(words, caseFunctions, {leading, extension}) {
  74. const replacements = words
  75. .map(({word, ignored}) => ignored ? [word] : caseFunctions.map(caseFunction => caseFunction(word)));
  76. const {
  77. samples: combinations,
  78. } = cartesianProductSamples(replacements);
  79. return [...new Set(combinations.map(parts => `${leading}${parts.join('')}${extension.toLowerCase()}`))];
  80. }
  81. const leadingUnderscoresRegex = /^(?<leading>_+)(?<tailing>.*)$/;
  82. function splitFilename(filename) {
  83. const result = leadingUnderscoresRegex.exec(filename) || {groups: {}};
  84. const {leading = '', tailing = filename} = result.groups;
  85. const words = [];
  86. let lastWord;
  87. for (const char of tailing) {
  88. const isIgnored = isIgnoredChar(char);
  89. if (lastWord?.ignored === isIgnored) {
  90. lastWord.word += char;
  91. } else {
  92. lastWord = {
  93. word: char,
  94. ignored: isIgnored,
  95. };
  96. words.push(lastWord);
  97. }
  98. }
  99. return {
  100. leading,
  101. words,
  102. };
  103. }
  104. /**
  105. Turns `[a, b, c]` into `a, b, or c`.
  106. @param {string[]} words
  107. @returns {string}
  108. */
  109. const englishishJoinWords = words => new Intl.ListFormat('en-US', {type: 'disjunction'}).format(words);
  110. /** @param {import('eslint').Rule.RuleContext} context */
  111. const create = context => {
  112. const options = context.options[0] || {};
  113. const chosenCases = getChosenCases(options);
  114. const ignore = (options.ignore || []).map(item => {
  115. if (item instanceof RegExp) {
  116. return item;
  117. }
  118. return new RegExp(item, 'u');
  119. });
  120. const chosenCasesFunctions = chosenCases.map(case_ => ignoreNumbers(cases[case_].fn));
  121. const filenameWithExtension = context.getPhysicalFilename();
  122. if (filenameWithExtension === '<input>' || filenameWithExtension === '<text>') {
  123. return;
  124. }
  125. return {
  126. Program() {
  127. const extension = path.extname(filenameWithExtension);
  128. const filename = path.basename(filenameWithExtension, extension);
  129. const base = filename + extension;
  130. if (ignoredByDefault.has(base) || ignore.some(regexp => regexp.test(base))) {
  131. return;
  132. }
  133. const {leading, words} = splitFilename(filename);
  134. const isValid = validateFilename(words, chosenCasesFunctions);
  135. if (isValid) {
  136. if (!isLowerCase(extension)) {
  137. return {
  138. loc: {column: 0, line: 1},
  139. messageId: MESSAGE_ID_EXTENSION,
  140. data: {filename: filename + extension.toLowerCase(), extension},
  141. };
  142. }
  143. return;
  144. }
  145. const renamedFilenames = fixFilename(words, chosenCasesFunctions, {
  146. leading,
  147. extension,
  148. });
  149. return {
  150. // Report on first character like `unicode-bom` rule
  151. // https://github.com/eslint/eslint/blob/8a77b661bc921c3408bae01b3aa41579edfc6e58/lib/rules/unicode-bom.js#L46
  152. loc: {column: 0, line: 1},
  153. messageId: MESSAGE_ID,
  154. data: {
  155. chosenCases: englishishJoinWords(chosenCases.map(x => cases[x].name)),
  156. renamedFilenames: englishishJoinWords(renamedFilenames.map(x => `\`${x}\``)),
  157. },
  158. };
  159. },
  160. };
  161. };
  162. const schema = [
  163. {
  164. oneOf: [
  165. {
  166. properties: {
  167. case: {
  168. enum: [
  169. 'camelCase',
  170. 'snakeCase',
  171. 'kebabCase',
  172. 'pascalCase',
  173. ],
  174. },
  175. ignore: {
  176. type: 'array',
  177. uniqueItems: true,
  178. },
  179. },
  180. additionalProperties: false,
  181. },
  182. {
  183. properties: {
  184. cases: {
  185. properties: {
  186. camelCase: {
  187. type: 'boolean',
  188. },
  189. snakeCase: {
  190. type: 'boolean',
  191. },
  192. kebabCase: {
  193. type: 'boolean',
  194. },
  195. pascalCase: {
  196. type: 'boolean',
  197. },
  198. },
  199. additionalProperties: false,
  200. },
  201. ignore: {
  202. type: 'array',
  203. uniqueItems: true,
  204. },
  205. },
  206. additionalProperties: false,
  207. },
  208. ],
  209. },
  210. ];
  211. /** @type {import('eslint').Rule.RuleModule} */
  212. module.exports = {
  213. create,
  214. meta: {
  215. type: 'suggestion',
  216. docs: {
  217. description: 'Enforce a case style for filenames.',
  218. },
  219. schema,
  220. messages,
  221. },
  222. };