source: frontend/node_modules/case-sensitive-paths-webpack-plugin/index.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 9.1 KB
RevLine 
[9af201e]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.logger = this.options.logger || console;
36 this.pathCache = new Map();
37 this.reset();
38}
39
40CaseSensitivePathsPlugin.prototype.reset = function() {
41 this.pathCache = new Map();
42 this.fsOperations = 0;
43 this.primed = false;
44};
45
46CaseSensitivePathsPlugin.prototype.getFilenamesInDir = function(dir, callback) {
47 const that = this;
48 const fs = this.compiler.inputFileSystem;
49 this.fsOperations += 1;
50
51 if (this.pathCache.has(dir)) {
52 callback(this.pathCache.get(dir));
53 return;
54 }
55 if (this.options.debug) {
56 this.logger.log('[CaseSensitivePathsPlugin] Reading directory', dir);
57 }
58
59 fs.readdir(dir, (err, files) => {
60 if (err) {
61 if (that.options.debug) {
62 this.logger.log(
63 '[CaseSensitivePathsPlugin] Failed to read directory',
64 dir,
65 err,
66 );
67 }
68 callback([]);
69 return;
70 }
71
72 callback(files.map((f) => (f.normalize ? f.normalize('NFC') : f)));
73 });
74};
75
76// This function based on code found at http://stackoverflow.com/questions/27367261/check-if-file-exists-case-sensitive
77// By Patrick McElhaney (No license indicated - Stack Overflow Answer)
78// This version will return with the real name of any incorrectly-cased portion of the path, null otherwise.
79CaseSensitivePathsPlugin.prototype.fileExistsWithCase = function(
80 filepath,
81 callback,
82) {
83 // Split filepath into current filename (or directory name) and parent directory tree.
84 const that = this;
85 const dir = path.dirname(filepath);
86 const filename = path.basename(filepath);
87 const parsedPath = path.parse(dir);
88
89 // If we are at the root, or have found a path we already know is good, return.
90 if (
91 parsedPath.dir === parsedPath.root ||
92 dir === '.' ||
93 that.pathCache.has(filepath)
94 ) {
95 callback();
96 return;
97 }
98
99 // Check all filenames in the current dir against current filename to ensure one of them matches.
100 // Read from the cache if available, from FS if not.
101 that.getFilenamesInDir(dir, (filenames) => {
102 // If the exact match does not exist, attempt to find the correct filename.
103 if (filenames.indexOf(filename) === -1) {
104 // Fallback value which triggers us to abort.
105 let correctFilename = '!nonexistent';
106
107 for (let i = 0; i < filenames.length; i += 1) {
108 if (filenames[i].toLowerCase() === filename.toLowerCase()) {
109 correctFilename = `\`${filenames[i]}\`.`;
110 break;
111 }
112 }
113 callback(correctFilename);
114 return;
115 }
116
117 // If exact match exists, recurse through directory tree until root.
118 that.fileExistsWithCase(dir, (recurse) => {
119 // If found an error elsewhere, return that correct filename
120 // Don't bother caching - we're about to error out anyway.
121 if (!recurse) {
122 that.pathCache.set(dir, filenames);
123 }
124
125 callback(recurse);
126 });
127 });
128};
129
130CaseSensitivePathsPlugin.prototype.primeCache = function(callback) {
131 if (this.primed) {
132 callback();
133 return;
134 }
135
136 const that = this;
137 // Prime the cache with the current directory. We have to assume the current casing is correct,
138 // as in certain circumstances people can switch into an incorrectly-cased directory.
139 const currentPath = path.resolve();
140 that.getFilenamesInDir(currentPath, (files) => {
141 that.pathCache.set(currentPath,files);
142 that.primed = true;
143 callback();
144 });
145};
146
147CaseSensitivePathsPlugin.prototype.apply = function(compiler) {
148 this.compiler = compiler;
149
150 const onDone = () => {
151 if (this.options.debug) {
152 this.logger.log(
153 '[CaseSensitivePathsPlugin] Total filesystem reads:',
154 this.fsOperations,
155 );
156 }
157
158 this.reset();
159 };
160
161 const checkFile = (pathName, data, done) => {
162 this.fileExistsWithCase(pathName, (realName) => {
163 if (realName) {
164 if (realName === '!nonexistent') {
165 // If file does not exist, let Webpack show a more appropriate error.
166 if (data.createData) done(null);
167 else done(null, data);
168 } else {
169 done(
170 new Error(
171 `[CaseSensitivePathsPlugin] \`${pathName}\` does not match the corresponding path on disk ${realName}`,
172 ),
173 );
174 }
175 } else if (data.createData) {
176 done(null);
177 } else {
178 done(null, data);
179 }
180 });
181 };
182
183 const cleanupPath = (resourcePath) => {
184 // Trim ? off, since some loaders add that to the resource they're attemping to load
185 return resourcePath.split('?')[0]
186 // replace escaped \0# with # see: https://github.com/webpack/enhanced-resolve#escaping
187 .replace('\u0000#', '#');
188 }
189
190 const onAfterResolve = (data, done) => {
191 this.primeCache(() => {
192
193 let pathName = cleanupPath((data.createData || data).resource);
194 pathName = pathName.normalize ? pathName.normalize('NFC') : pathName;
195
196 checkFile(pathName, data, done);
197 });
198 };
199
200 if (compiler.hooks) {
201 compiler.hooks.done.tap('CaseSensitivePathsPlugin', onDone);
202 if (this.options.useBeforeEmitHook) {
203 if (this.options.debug) {
204 this.logger.log(
205 '[CaseSensitivePathsPlugin] Using the hook for before emit.',
206 );
207 }
208 compiler.hooks.emit.tapAsync(
209 'CaseSensitivePathsPlugin',
210 (compilation, callback) => {
211 let resolvedFilesCount = 0;
212 const errors = [];
213 this.primeCache(() => {
214 compilation.fileDependencies.forEach((filename) => {
215 checkFile(filename, filename, (error) => {
216 resolvedFilesCount += 1;
217 if (error) {
218 errors.push(error);
219 }
220 if (resolvedFilesCount === compilation.fileDependencies.size) {
221 if (errors.length) {
222 // Send all errors to webpack
223 Array.prototype.push.apply(compilation.errors, errors);
224 }
225 callback();
226 }
227 });
228 });
229 });
230 },
231 );
232 } else {
233 compiler.hooks.normalModuleFactory.tap(
234 'CaseSensitivePathsPlugin',
235 (nmf) => {
236 nmf.hooks.afterResolve.tapAsync(
237 'CaseSensitivePathsPlugin',
238 onAfterResolve,
239 );
240 },
241 );
242 }
243 } else {
244 compiler.plugin('done', onDone);
245 compiler.plugin('normal-module-factory', (nmf) => {
246 nmf.plugin('after-resolve', onAfterResolve);
247 });
248 }
249};
250
251module.exports = CaseSensitivePathsPlugin;
Note: See TracBrowser for help on using the repository browser.