UNPKG

10.3 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Sergey Melyukov @smelukov
4*/
5
6"use strict";
7
8const asyncLib = require("neo-async");
9const { SyncBailHook } = require("tapable");
10const Compilation = require("../lib/Compilation");
11const createSchemaValidation = require("./util/create-schema-validation");
12const { join } = require("./util/fs");
13const processAsyncTree = require("./util/processAsyncTree");
14
15/** @typedef {import("../declarations/WebpackOptions").CleanOptions} CleanOptions */
16/** @typedef {import("./Compiler")} Compiler */
17/** @typedef {import("./logging/Logger").Logger} Logger */
18/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */
19/** @typedef {import("./util/fs").StatsCallback} StatsCallback */
20
21/** @typedef {(function(string):boolean)|RegExp} IgnoreItem */
22/** @typedef {function(IgnoreItem): void} AddToIgnoreCallback */
23
24/**
25 * @typedef {Object} CleanPluginCompilationHooks
26 * @property {SyncBailHook<[string], boolean>} keep when returning true the file/directory will be kept during cleaning, returning false will clean it and ignore the following plugins and config
27 */
28
29const validate = createSchemaValidation(
30 undefined,
31 () => {
32 const { definitions } = require("../schemas/WebpackOptions.json");
33 return {
34 definitions,
35 oneOf: [{ $ref: "#/definitions/CleanOptions" }]
36 };
37 },
38 {
39 name: "Clean Plugin",
40 baseDataPath: "options"
41 }
42);
43
44/**
45 * @param {OutputFileSystem} fs filesystem
46 * @param {string} outputPath output path
47 * @param {Set<string>} currentAssets filename of the current assets (must not start with .. or ., must only use / as path separator)
48 * @param {function((Error | null)=, Set<string>=): void} callback returns the filenames of the assets that shouldn't be there
49 * @returns {void}
50 */
51const getDiffToFs = (fs, outputPath, currentAssets, callback) => {
52 const directories = new Set();
53 // get directories of assets
54 for (const asset of currentAssets) {
55 directories.add(asset.replace(/(^|\/)[^/]*$/, ""));
56 }
57 // and all parent directories
58 for (const directory of directories) {
59 directories.add(directory.replace(/(^|\/)[^/]*$/, ""));
60 }
61 const diff = new Set();
62 asyncLib.forEachLimit(
63 directories,
64 10,
65 (directory, callback) => {
66 fs.readdir(join(fs, outputPath, directory), (err, entries) => {
67 if (err) {
68 if (err.code === "ENOENT") return callback();
69 if (err.code === "ENOTDIR") {
70 diff.add(directory);
71 return callback();
72 }
73 return callback(err);
74 }
75 for (const entry of entries) {
76 const file = /** @type {string} */ (entry);
77 const filename = directory ? `${directory}/${file}` : file;
78 if (!directories.has(filename) && !currentAssets.has(filename)) {
79 diff.add(filename);
80 }
81 }
82 callback();
83 });
84 },
85 err => {
86 if (err) return callback(err);
87
88 callback(null, diff);
89 }
90 );
91};
92
93/**
94 * @param {Set<string>} currentAssets assets list
95 * @param {Set<string>} oldAssets old assets list
96 * @returns {Set<string>} diff
97 */
98const getDiffToOldAssets = (currentAssets, oldAssets) => {
99 const diff = new Set();
100 for (const asset of oldAssets) {
101 if (!currentAssets.has(asset)) diff.add(asset);
102 }
103 return diff;
104};
105
106/**
107 * @param {OutputFileSystem} fs filesystem
108 * @param {string} filename path to file
109 * @param {StatsCallback} callback callback for provided filename
110 * @returns {void}
111 */
112const doStat = (fs, filename, callback) => {
113 if ("lstat" in fs) {
114 fs.lstat(filename, callback);
115 } else {
116 fs.stat(filename, callback);
117 }
118};
119
120/**
121 * @param {OutputFileSystem} fs filesystem
122 * @param {string} outputPath output path
123 * @param {boolean} dry only log instead of fs modification
124 * @param {Logger} logger logger
125 * @param {Set<string>} diff filenames of the assets that shouldn't be there
126 * @param {function(string): boolean} isKept check if the entry is ignored
127 * @param {function(Error=): void} callback callback
128 * @returns {void}
129 */
130const applyDiff = (fs, outputPath, dry, logger, diff, isKept, callback) => {
131 const log = msg => {
132 if (dry) {
133 logger.info(msg);
134 } else {
135 logger.log(msg);
136 }
137 };
138 /** @typedef {{ type: "check" | "unlink" | "rmdir", filename: string, parent: { remaining: number, job: Job } | undefined }} Job */
139 /** @type {Job[]} */
140 const jobs = Array.from(diff, filename => ({
141 type: "check",
142 filename,
143 parent: undefined
144 }));
145 processAsyncTree(
146 jobs,
147 10,
148 ({ type, filename, parent }, push, callback) => {
149 const handleError = err => {
150 if (err.code === "ENOENT") {
151 log(`${filename} was removed during cleaning by something else`);
152 handleParent();
153 return callback();
154 }
155 return callback(err);
156 };
157 const handleParent = () => {
158 if (parent && --parent.remaining === 0) push(parent.job);
159 };
160 const path = join(fs, outputPath, filename);
161 switch (type) {
162 case "check":
163 if (isKept(filename)) {
164 // do not decrement parent entry as we don't want to delete the parent
165 log(`${filename} will be kept`);
166 return process.nextTick(callback);
167 }
168 doStat(fs, path, (err, stats) => {
169 if (err) return handleError(err);
170 if (!stats.isDirectory()) {
171 push({
172 type: "unlink",
173 filename,
174 parent
175 });
176 return callback();
177 }
178 fs.readdir(path, (err, entries) => {
179 if (err) return handleError(err);
180 /** @type {Job} */
181 const deleteJob = {
182 type: "rmdir",
183 filename,
184 parent
185 };
186 if (entries.length === 0) {
187 push(deleteJob);
188 } else {
189 const parentToken = {
190 remaining: entries.length,
191 job: deleteJob
192 };
193 for (const entry of entries) {
194 const file = /** @type {string} */ (entry);
195 if (file.startsWith(".")) {
196 log(
197 `${filename} will be kept (dot-files will never be removed)`
198 );
199 continue;
200 }
201 push({
202 type: "check",
203 filename: `${filename}/${file}`,
204 parent: parentToken
205 });
206 }
207 }
208 return callback();
209 });
210 });
211 break;
212 case "rmdir":
213 log(`${filename} will be removed`);
214 if (dry) {
215 handleParent();
216 return process.nextTick(callback);
217 }
218 if (!fs.rmdir) {
219 logger.warn(
220 `${filename} can't be removed because output file system doesn't support removing directories (rmdir)`
221 );
222 return process.nextTick(callback);
223 }
224 fs.rmdir(path, err => {
225 if (err) return handleError(err);
226 handleParent();
227 callback();
228 });
229 break;
230 case "unlink":
231 log(`${filename} will be removed`);
232 if (dry) {
233 handleParent();
234 return process.nextTick(callback);
235 }
236 if (!fs.unlink) {
237 logger.warn(
238 `${filename} can't be removed because output file system doesn't support removing files (rmdir)`
239 );
240 return process.nextTick(callback);
241 }
242 fs.unlink(path, err => {
243 if (err) return handleError(err);
244 handleParent();
245 callback();
246 });
247 break;
248 }
249 },
250 callback
251 );
252};
253
254/** @type {WeakMap<Compilation, CleanPluginCompilationHooks>} */
255const compilationHooksMap = new WeakMap();
256
257class CleanPlugin {
258 /**
259 * @param {Compilation} compilation the compilation
260 * @returns {CleanPluginCompilationHooks} the attached hooks
261 */
262 static getCompilationHooks(compilation) {
263 if (!(compilation instanceof Compilation)) {
264 throw new TypeError(
265 "The 'compilation' argument must be an instance of Compilation"
266 );
267 }
268 let hooks = compilationHooksMap.get(compilation);
269 if (hooks === undefined) {
270 hooks = {
271 /** @type {SyncBailHook<[string], boolean>} */
272 keep: new SyncBailHook(["ignore"])
273 };
274 compilationHooksMap.set(compilation, hooks);
275 }
276 return hooks;
277 }
278
279 /** @param {CleanOptions} options options */
280 constructor(options = {}) {
281 validate(options);
282 this.options = { dry: false, ...options };
283 }
284
285 /**
286 * Apply the plugin
287 * @param {Compiler} compiler the compiler instance
288 * @returns {void}
289 */
290 apply(compiler) {
291 const { dry, keep } = this.options;
292
293 const keepFn =
294 typeof keep === "function"
295 ? keep
296 : typeof keep === "string"
297 ? path => path.startsWith(keep)
298 : typeof keep === "object" && keep.test
299 ? path => keep.test(path)
300 : () => false;
301
302 // We assume that no external modification happens while the compiler is active
303 // So we can store the old assets and only diff to them to avoid fs access on
304 // incremental builds
305 let oldAssets;
306
307 compiler.hooks.emit.tapAsync(
308 {
309 name: "CleanPlugin",
310 stage: 100
311 },
312 (compilation, callback) => {
313 const hooks = CleanPlugin.getCompilationHooks(compilation);
314 const logger = compilation.getLogger("webpack.CleanPlugin");
315 const fs = compiler.outputFileSystem;
316
317 if (!fs.readdir) {
318 return callback(
319 new Error(
320 "CleanPlugin: Output filesystem doesn't support listing directories (readdir)"
321 )
322 );
323 }
324
325 const currentAssets = new Set();
326 for (const asset of Object.keys(compilation.assets)) {
327 if (/^[A-Za-z]:\\|^\/|^\\\\/.test(asset)) continue;
328 let normalizedAsset;
329 let newNormalizedAsset = asset.replace(/\\/g, "/");
330 do {
331 normalizedAsset = newNormalizedAsset;
332 newNormalizedAsset = normalizedAsset.replace(
333 /(^|\/)(?!\.\.)[^/]+\/\.\.\//g,
334 "$1"
335 );
336 } while (newNormalizedAsset !== normalizedAsset);
337 if (normalizedAsset.startsWith("../")) continue;
338 currentAssets.add(normalizedAsset);
339 }
340
341 const outputPath = compilation.getPath(compiler.outputPath, {});
342
343 const isKept = path => {
344 const result = hooks.keep.call(path);
345 if (result !== undefined) return result;
346 return keepFn(path);
347 };
348
349 const diffCallback = (err, diff) => {
350 if (err) {
351 oldAssets = undefined;
352 return callback(err);
353 }
354 applyDiff(fs, outputPath, dry, logger, diff, isKept, err => {
355 if (err) {
356 oldAssets = undefined;
357 } else {
358 oldAssets = currentAssets;
359 }
360 callback(err);
361 });
362 };
363
364 if (oldAssets) {
365 diffCallback(null, getDiffToOldAssets(currentAssets, oldAssets));
366 } else {
367 getDiffToFs(fs, outputPath, currentAssets, diffCallback);
368 }
369 }
370 );
371 }
372}
373
374module.exports = CleanPlugin;