index.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. /* eslint-disable strict */
  2. 'use strict';
  3. /* This plugin based on https://gist.github.com/Morhaus/333579c2a5b4db644bd5
  4. Original license:
  5. --------
  6. The MIT License (MIT)
  7. Copyright (c) 2015 Alexandre Kirszenberg
  8. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  9. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  10. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  11. --------
  12. And it's NPM-ified version: https://github.com/dcousineau/force-case-sensitivity-webpack-plugin
  13. Author Daniel Cousineau indicated MIT license as well but did not include it
  14. The originals did not properly case-sensitize the entire path, however. This plugin resolves that issue.
  15. This plugin license, also MIT:
  16. --------
  17. The MIT License (MIT)
  18. Copyright (c) 2016 Michael Pratt
  19. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  20. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  21. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. --------
  23. */
  24. const path = require('path');
  25. function CaseSensitivePathsPlugin(options) {
  26. this.options = options || {};
  27. this.reset();
  28. }
  29. CaseSensitivePathsPlugin.prototype.reset = function () {
  30. this.pathCache = {};
  31. this.fsOperations = 0;
  32. this.primed = false;
  33. };
  34. CaseSensitivePathsPlugin.prototype.getFilenamesInDir = function (dir, callback) {
  35. const that = this;
  36. const fs = this.compiler.inputFileSystem;
  37. this.fsOperations += 1;
  38. if (Object.prototype.hasOwnProperty.call(this.pathCache, dir)) {
  39. callback(this.pathCache[dir]);
  40. return;
  41. }
  42. if (this.options.debug) {
  43. console.log('[CaseSensitivePathsPlugin] Reading directory', dir);
  44. }
  45. fs.readdir(dir, (err, files) => {
  46. if (err) {
  47. if (that.options.debug) {
  48. console.log('[CaseSensitivePathsPlugin] Failed to read directory', dir, err);
  49. }
  50. callback([]);
  51. return;
  52. }
  53. callback(files.map(f => f.normalize ? f.normalize('NFC') : f));
  54. });
  55. };
  56. // This function based on code found at http://stackoverflow.com/questions/27367261/check-if-file-exists-case-sensitive
  57. // By Patrick McElhaney (No license indicated - Stack Overflow Answer)
  58. // This version will return with the real name of any incorrectly-cased portion of the path, null otherwise.
  59. CaseSensitivePathsPlugin.prototype.fileExistsWithCase = function (filepath, callback) {
  60. // Split filepath into current filename (or directory name) and parent directory tree.
  61. const that = this;
  62. const dir = path.dirname(filepath);
  63. const filename = path.basename(filepath);
  64. const parsedPath = path.parse(dir);
  65. // If we are at the root, or have found a path we already know is good, return.
  66. if (parsedPath.dir === parsedPath.root || dir === '.' || Object.prototype.hasOwnProperty.call(that.pathCache, filepath)) {
  67. callback();
  68. return;
  69. }
  70. // Check all filenames in the current dir against current filename to ensure one of them matches.
  71. // Read from the cache if available, from FS if not.
  72. that.getFilenamesInDir(dir, (filenames) => {
  73. // If the exact match does not exist, attempt to find the correct filename.
  74. if (filenames.indexOf(filename) === -1) {
  75. // Fallback value which triggers us to abort.
  76. let correctFilename = '!nonexistent';
  77. for (let i = 0; i < filenames.length; i += 1) {
  78. if (filenames[i].toLowerCase() === filename.toLowerCase()) {
  79. correctFilename = `\`${filenames[i]}\`.`;
  80. break;
  81. }
  82. }
  83. callback(correctFilename);
  84. return;
  85. }
  86. // If exact match exists, recurse through directory tree until root.
  87. that.fileExistsWithCase(dir, (recurse) => {
  88. // If found an error elsewhere, return that correct filename
  89. // Don't bother caching - we're about to error out anyway.
  90. if (!recurse) {
  91. that.pathCache[dir] = filenames;
  92. }
  93. callback(recurse);
  94. });
  95. });
  96. };
  97. CaseSensitivePathsPlugin.prototype.primeCache = function (callback) {
  98. if (this.primed) {
  99. callback();
  100. return;
  101. }
  102. const that = this;
  103. // Prime the cache with the current directory. We have to assume the current casing is correct,
  104. // as in certain circumstances people can switch into an incorrectly-cased directory.
  105. const currentPath = path.resolve();
  106. that.getFilenamesInDir(currentPath, (files) => {
  107. that.pathCache[currentPath] = files;
  108. that.primed = true;
  109. callback();
  110. });
  111. };
  112. CaseSensitivePathsPlugin.prototype.apply = function (compiler) {
  113. this.compiler = compiler;
  114. const onDone = () => {
  115. if (this.options.debug) {
  116. console.log('[CaseSensitivePathsPlugin] Total filesystem reads:', this.fsOperations);
  117. }
  118. this.reset();
  119. };
  120. const checkFile = (pathName, data, done) => {
  121. this.fileExistsWithCase(pathName, (realName) => {
  122. if (realName) {
  123. if (realName === '!nonexistent') {
  124. // If file does not exist, let Webpack show a more appropriate error.
  125. done(null, data);
  126. } else {
  127. done(new Error(`[CaseSensitivePathsPlugin] \`${pathName}\` does not match the corresponding path on disk ${realName}`));
  128. }
  129. } else {
  130. done(null, data);
  131. }
  132. });
  133. };
  134. const onAfterResolve = (data, done) => {
  135. this.primeCache(() => {
  136. // Trim ? off, since some loaders add that to the resource they're attemping to load
  137. let pathName = data.resource.split('?')[0];
  138. pathName = pathName.normalize ? pathName.normalize('NFC') : pathName;
  139. checkFile(pathName, data, done);
  140. });
  141. };
  142. if (compiler.hooks) {
  143. compiler.hooks.done.tap('CaseSensitivePathsPlugin', onDone);
  144. if (this.options.useBeforeEmitHook) {
  145. if (this.options.debug) {
  146. console.log('[CaseSensitivePathsPlugin] Using the hook for before emit.');
  147. }
  148. compiler.hooks.emit.tapAsync('CaseSensitivePathsPlugin', (compilation, callback) => {
  149. let resolvedFilesCount = 0;
  150. const errors = [];
  151. this.primeCache(() => {
  152. compilation.fileDependencies.forEach((filename) => {
  153. checkFile(filename, filename, (error) => {
  154. resolvedFilesCount += 1;
  155. if (error) {
  156. errors.push(error);
  157. }
  158. if (resolvedFilesCount === compilation.fileDependencies.size) {
  159. if (errors.length) {
  160. // Send all errors to webpack
  161. Array.prototype.push.apply(compilation.errors, errors);
  162. }
  163. callback();
  164. }
  165. });
  166. });
  167. });
  168. });
  169. } else {
  170. compiler.hooks.normalModuleFactory.tap('CaseSensitivePathsPlugin', (nmf) => {
  171. nmf.hooks.afterResolve.tapAsync('CaseSensitivePathsPlugin', onAfterResolve);
  172. });
  173. }
  174. } else {
  175. compiler.plugin('done', onDone);
  176. compiler.plugin('normal-module-factory', (nmf) => {
  177. nmf.plugin('after-resolve', onAfterResolve);
  178. });
  179. }
  180. };
  181. module.exports = CaseSensitivePathsPlugin;