CleanPlugin.js 11 KB

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