CleanPlugin.js 12 KB

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