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