CleanPlugin.js 12 KB

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