filename-case.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. 'use strict';
  2. const path = require('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 && 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. function englishishJoinWords(words) {
  110. if (words.length === 1) {
  111. return words[0];
  112. }
  113. if (words.length === 2) {
  114. return `${words[0]} or ${words[1]}`;
  115. }
  116. return `${words.slice(0, -1).join(', ')}, or ${words[words.length - 1]}`;
  117. }
  118. /** @param {import('eslint').Rule.RuleContext} context */
  119. const create = context => {
  120. const options = context.options[0] || {};
  121. const chosenCases = getChosenCases(options);
  122. const ignore = (options.ignore || []).map(item => {
  123. if (item instanceof RegExp) {
  124. return item;
  125. }
  126. return new RegExp(item, 'u');
  127. });
  128. const chosenCasesFunctions = chosenCases.map(case_ => ignoreNumbers(cases[case_].fn));
  129. const filenameWithExtension = context.getPhysicalFilename();
  130. if (filenameWithExtension === '<input>' || filenameWithExtension === '<text>') {
  131. return {};
  132. }
  133. return {
  134. Program() {
  135. const extension = path.extname(filenameWithExtension);
  136. const filename = path.basename(filenameWithExtension, extension);
  137. const base = filename + extension;
  138. if (ignoredByDefault.has(base) || ignore.some(regexp => regexp.test(base))) {
  139. return;
  140. }
  141. const {leading, words} = splitFilename(filename);
  142. const isValid = validateFilename(words, chosenCasesFunctions);
  143. if (isValid) {
  144. if (!isLowerCase(extension)) {
  145. return {
  146. loc: {column: 0, line: 1},
  147. messageId: MESSAGE_ID_EXTENSION,
  148. data: {filename: filename + extension.toLowerCase(), extension},
  149. };
  150. }
  151. return;
  152. }
  153. const renamedFilenames = fixFilename(words, chosenCasesFunctions, {
  154. leading,
  155. extension,
  156. });
  157. return {
  158. // Report on first character like `unicode-bom` rule
  159. // https://github.com/eslint/eslint/blob/8a77b661bc921c3408bae01b3aa41579edfc6e58/lib/rules/unicode-bom.js#L46
  160. loc: {column: 0, line: 1},
  161. messageId: MESSAGE_ID,
  162. data: {
  163. chosenCases: englishishJoinWords(chosenCases.map(x => cases[x].name)),
  164. renamedFilenames: englishishJoinWords(renamedFilenames.map(x => `\`${x}\``)),
  165. },
  166. };
  167. },
  168. };
  169. };
  170. const schema = [
  171. {
  172. oneOf: [
  173. {
  174. properties: {
  175. case: {
  176. enum: [
  177. 'camelCase',
  178. 'snakeCase',
  179. 'kebabCase',
  180. 'pascalCase',
  181. ],
  182. },
  183. ignore: {
  184. type: 'array',
  185. uniqueItems: true,
  186. },
  187. },
  188. additionalProperties: false,
  189. },
  190. {
  191. properties: {
  192. cases: {
  193. properties: {
  194. camelCase: {
  195. type: 'boolean',
  196. },
  197. snakeCase: {
  198. type: 'boolean',
  199. },
  200. kebabCase: {
  201. type: 'boolean',
  202. },
  203. pascalCase: {
  204. type: 'boolean',
  205. },
  206. },
  207. additionalProperties: false,
  208. },
  209. ignore: {
  210. type: 'array',
  211. uniqueItems: true,
  212. },
  213. },
  214. additionalProperties: false,
  215. },
  216. ],
  217. },
  218. ];
  219. /** @type {import('eslint').Rule.RuleModule} */
  220. module.exports = {
  221. create,
  222. meta: {
  223. type: 'suggestion',
  224. docs: {
  225. description: 'Enforce a case style for filenames.',
  226. },
  227. schema,
  228. messages,
  229. },
  230. };