UNPKG

8.6 kBJavaScriptView Raw
1/* eslint-disable strict */
2
3'use strict';
4
5/* This plugin based on https://gist.github.com/Morhaus/333579c2a5b4db644bd5
6
7 Original license:
8 --------
9 The MIT License (MIT)
10 Copyright (c) 2015 Alexandre Kirszenberg
11 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:
12 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
13 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.
14 --------
15
16 And it's NPM-ified version: https://github.com/dcousineau/force-case-sensitivity-webpack-plugin
17 Author Daniel Cousineau indicated MIT license as well but did not include it
18
19 The originals did not properly case-sensitize the entire path, however. This plugin resolves that issue.
20
21 This plugin license, also MIT:
22 --------
23 The MIT License (MIT)
24 Copyright (c) 2016 Michael Pratt
25 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:
26 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
27 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.
28 --------
29 */
30
31const path = require('path');
32
33function CaseSensitivePathsPlugin(options) {
34 this.options = options || {};
35 this.reset();
36}
37
38CaseSensitivePathsPlugin.prototype.reset = function () {
39 this.pathCache = {};
40 this.fsOperations = 0;
41 this.primed = false;
42};
43
44CaseSensitivePathsPlugin.prototype.getFilenamesInDir = function (dir, callback) {
45 const that = this;
46 const fs = this.compiler.inputFileSystem;
47 this.fsOperations += 1;
48
49 if (Object.prototype.hasOwnProperty.call(this.pathCache, dir)) {
50 callback(this.pathCache[dir]);
51 return;
52 }
53 if (this.options.debug) {
54 console.log('[CaseSensitivePathsPlugin] Reading directory', dir);
55 }
56
57 fs.readdir(dir, (err, files) => {
58 if (err) {
59 if (that.options.debug) {
60 console.log('[CaseSensitivePathsPlugin] Failed to read directory', dir, err);
61 }
62 callback([]);
63 return;
64 }
65
66 callback(files.map(f => f.normalize ? f.normalize('NFC') : f));
67 });
68};
69
70// This function based on code found at http://stackoverflow.com/questions/27367261/check-if-file-exists-case-sensitive
71// By Patrick McElhaney (No license indicated - Stack Overflow Answer)
72// This version will return with the real name of any incorrectly-cased portion of the path, null otherwise.
73CaseSensitivePathsPlugin.prototype.fileExistsWithCase = function (filepath, callback) {
74 // Split filepath into current filename (or directory name) and parent directory tree.
75 const that = this;
76 const dir = path.dirname(filepath);
77 const filename = path.basename(filepath);
78 const parsedPath = path.parse(dir);
79
80 // If we are at the root, or have found a path we already know is good, return.
81 if (parsedPath.dir === parsedPath.root || dir === '.' || Object.prototype.hasOwnProperty.call(that.pathCache, filepath)) {
82 callback();
83 return;
84 }
85
86 // Check all filenames in the current dir against current filename to ensure one of them matches.
87 // Read from the cache if available, from FS if not.
88 that.getFilenamesInDir(dir, (filenames) => {
89 // If the exact match does not exist, attempt to find the correct filename.
90 if (filenames.indexOf(filename) === -1) {
91 // Fallback value which triggers us to abort.
92 let correctFilename = '!nonexistent';
93
94 for (let i = 0; i < filenames.length; i += 1) {
95 if (filenames[i].toLowerCase() === filename.toLowerCase()) {
96 correctFilename = `\`${filenames[i]}\`.`;
97 break;
98 }
99 }
100 callback(correctFilename);
101 return;
102 }
103
104 // If exact match exists, recurse through directory tree until root.
105 that.fileExistsWithCase(dir, (recurse) => {
106 // If found an error elsewhere, return that correct filename
107 // Don't bother caching - we're about to error out anyway.
108 if (!recurse) {
109 that.pathCache[dir] = filenames;
110 }
111
112 callback(recurse);
113 });
114 });
115};
116
117CaseSensitivePathsPlugin.prototype.primeCache = function (callback) {
118 if (this.primed) {
119 callback();
120 return;
121 }
122
123 const that = this;
124 // Prime the cache with the current directory. We have to assume the current casing is correct,
125 // as in certain circumstances people can switch into an incorrectly-cased directory.
126 const currentPath = path.resolve();
127 that.getFilenamesInDir(currentPath, (files) => {
128 that.pathCache[currentPath] = files;
129 that.primed = true;
130 callback();
131 });
132};
133
134CaseSensitivePathsPlugin.prototype.apply = function (compiler) {
135 this.compiler = compiler;
136
137 const onDone = () => {
138 if (this.options.debug) {
139 console.log('[CaseSensitivePathsPlugin] Total filesystem reads:', this.fsOperations);
140 }
141
142 this.reset();
143 };
144
145 const checkFile = (pathName, data, done) => {
146 this.fileExistsWithCase(pathName, (realName) => {
147 if (realName) {
148 if (realName === '!nonexistent') {
149 // If file does not exist, let Webpack show a more appropriate error.
150 done(null, data);
151 } else {
152 done(new Error(`[CaseSensitivePathsPlugin] \`${pathName}\` does not match the corresponding path on disk ${realName}`));
153 }
154 } else {
155 done(null, data);
156 }
157 });
158 };
159
160 const onAfterResolve = (data, done) => {
161 this.primeCache(() => {
162 // Trim ? off, since some loaders add that to the resource they're attemping to load
163 let pathName = data.resource.split('?')[0];
164 pathName = pathName.normalize ? pathName.normalize('NFC') : pathName;
165
166 checkFile(pathName, data, done);
167 });
168 };
169
170 if (compiler.hooks) {
171 compiler.hooks.done.tap('CaseSensitivePathsPlugin', onDone);
172 if (this.options.useBeforeEmitHook) {
173 if (this.options.debug) {
174 console.log('[CaseSensitivePathsPlugin] Using the hook for before emit.');
175 }
176 compiler.hooks.emit.tapAsync('CaseSensitivePathsPlugin', (compilation, callback) => {
177 let resolvedFilesCount = 0;
178 const errors = [];
179 this.primeCache(() => {
180 compilation.fileDependencies.forEach((filename) => {
181 checkFile(filename, filename, (error) => {
182 resolvedFilesCount += 1;
183 if (error) {
184 errors.push(error);
185 }
186 if (resolvedFilesCount === compilation.fileDependencies.size) {
187 if (errors.length) {
188 // Send all errors to webpack
189 Array.prototype.push.apply(compilation.errors, errors);
190 }
191 callback();
192 }
193 });
194 });
195 });
196 });
197 } else {
198 compiler.hooks.normalModuleFactory.tap('CaseSensitivePathsPlugin', (nmf) => {
199 nmf.hooks.afterResolve.tapAsync('CaseSensitivePathsPlugin', onAfterResolve);
200 });
201 }
202 } else {
203 compiler.plugin('done', onDone);
204 compiler.plugin('normal-module-factory', (nmf) => {
205 nmf.plugin('after-resolve', onAfterResolve);
206 });
207 }
208};
209
210module.exports = CaseSensitivePathsPlugin;