Repository: webpack-contrib/compression-webpack-plugin
Pull request #191 (2020-09-02 08:56:24)

Refactor code
<!--
  HOLY CRAP a Pull Request. We ❤️ those!

  If you remove or skip this template, you'll make the 🐼 sad and the mighty god
  of Github will appear and pile-drive the close button from a great height
  while making animal noises.

  Please place an x (no spaces!) in all [ ] that apply
-->

This PR contains a:

- [ ] **bugfix**
- [ ] new **feature**
- [x] **code refactor**
- [ ] **test update** <!-- if bug or feature is checked, this should be too -->
- [ ] **typo fix**
- [ ] **metadata update**

### Motivation / Use-Case

simplify code

### Breaking Changes

No

### Additional Info

No

codecov[bot]: # [Codecov](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/pull/191?src=pr&el=h1) Report
> Merging [#191](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/pull/191?src=pr&el=desc) into [master](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/commit/81bf60166caeeea9f5d5a18e1471ed0f7a28c312?el=desc) will **decrease** coverage by `11.03%`.
> The diff coverage is `84.12%`.

[![Impacted file tree graph](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/pull/191/graphs/tree.svg?width=650&height=150&src=pr&token=wLGv0aBxEE)](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/pull/191?src=pr&el=tree)

```diff
@@             Coverage Diff             @@
##           master     #191       +/-   ##
===========================================
- Coverage   97.02%   85.98%   -11.04%     
===========================================
  Files           4        4               
  Lines         168      157       -11     
  Branches       47       46        -1     
===========================================
- Hits          163      135       -28     
- Misses          3       20       +17     
  Partials        2        2               
```


| [Impacted Files](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/pull/191?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [src/Webpack5Cache.js](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/pull/191/diff?src=pr&el=tree#diff-c3JjL1dlYnBhY2s1Q2FjaGUuanM=) | `0.00% <0.00%> (-100.00%)` | :arrow_down: |
| [src/index.js](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/pull/191/diff?src=pr&el=tree#diff-c3JjL2luZGV4Lmpz) | `88.52% <91.66%> (-7.78%)` | :arrow_down: |
| [src/Webpack4Cache.js](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/pull/191/diff?src=pr&el=tree#diff-c3JjL1dlYnBhY2s0Q2FjaGUuanM=) | `100.00% <100.00%> (ø)` | |

------

[Continue to review full report at Codecov](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/pull/191?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/pull/191?src=pr&el=footer). Last update [81bf601...fc027a4](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/pull/191?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).


Patch:
diff --git a/src/Webpack4Cache.js b/src/Webpack4Cache.js
index 144b0ca..e53831f 100644
--- a/src/Webpack4Cache.js
+++ b/src/Webpack4Cache.js
@@ -17,8 +17,8 @@ export default class Webpack4Cache {
     return findCacheDir({ name: 'compression-webpack-plugin' }) || os.tmpdir();
   }
 
-  async get(task, sources) {
-    const weakOutput = this.weakCache.get(task.assetSource);
+  async get(cacheData, sources) {
+    const weakOutput = this.weakCache.get(cacheData.source);
 
     if (weakOutput) {
       return weakOutput;
@@ -30,12 +30,13 @@ export default class Webpack4Cache {
     }
 
     // eslint-disable-next-line no-param-reassign
-    task.cacheIdent = task.cacheIdent || serialize(task.cacheKeys);
+    cacheData.cacheIdent =
+      cacheData.cacheIdent || serialize(cacheData.cacheKeys);
 
     let cachedResult;
 
     try {
-      cachedResult = await cacache.get(this.cache, task.cacheIdent);
+      cachedResult = await cacache.get(this.cache, cacheData.cacheIdent);
     } catch (ignoreError) {
       // eslint-disable-next-line no-undefined
       return undefined;
@@ -46,9 +47,9 @@ export default class Webpack4Cache {
     );
   }
 
-  async store(task) {
-    if (!this.weakCache.has(task.assetSource)) {
-      this.weakCache.set(task.assetSource, task.output);
+  async store(cacheData) {
+    if (!this.weakCache.has(cacheData.source)) {
+      this.weakCache.set(cacheData.source, cacheData.output);
     }
 
     if (!this.cache) {
@@ -56,7 +57,7 @@ export default class Webpack4Cache {
       return undefined;
     }
 
-    const { cacheIdent, output } = task;
+    const { cacheIdent, output } = cacheData;
 
     return cacache.put(this.cache, cacheIdent, JSON.stringify(output.source()));
   }
diff --git a/src/Webpack5Cache.js b/src/Webpack5Cache.js
index 2bbcb89..2b9d32a 100644
--- a/src/Webpack5Cache.js
+++ b/src/Webpack5Cache.js
@@ -3,14 +3,19 @@ export default class Cache {
     this.cache = compilation.getCache('CompressionWebpackPlugin');
   }
 
-  async get(task) {
+  async get(cacheData) {
     // eslint-disable-next-line no-param-reassign
-    task.eTag = task.eTag || this.cache.getLazyHashedEtag(task.assetSource);
+    cacheData.eTag =
+      cacheData.eTag || this.cache.getLazyHashedEtag(cacheData.source);
 
-    return this.cache.getPromise(task.assetName, task.eTag);
+    return this.cache.getPromise(cacheData.assetName, cacheData.eTag);
   }
 
-  async store(task) {
-    return this.cache.storePromise(task.assetName, task.eTag, task.output);
+  async store(cacheData) {
+    return this.cache.storePromise(
+      cacheData.assetName,
+      cacheData.eTag,
+      cacheData.output
+    );
   }
 }
diff --git a/src/index.js b/src/index.js
index bc22f82..1119a8e 100644
--- a/src/index.js
+++ b/src/index.js
@@ -137,7 +137,7 @@ class CompressionPlugin {
     delete compilation.assets[name];
   }
 
-  compress(input) {
+  runCompressionAlgorithm(input) {
     return new Promise((resolve, reject) => {
       const { algorithm, compressionOptions } = this;
 
@@ -156,128 +156,121 @@ class CompressionPlugin {
     });
   }
 
-  *getTask(compilation, assetName) {
-    const { source: assetSource, info: assetInfo } = CompressionPlugin.getAsset(
-      compilation,
-      assetName
+  async compress(compilation, assets, CacheEngine, weakCache) {
+    const assetNames = Object.keys(
+      typeof assets === 'undefined' ? compilation.assets : assets
+    ).filter((assetName) =>
+      // eslint-disable-next-line no-undefined
+      ModuleFilenameHelpers.matchObject.bind(undefined, this.options)(assetName)
     );
 
-    if (assetInfo.compressed) {
-      yield false;
-    }
-
-    let relatedName;
-
-    if (typeof this.options.algorithm === 'function') {
-      let filenameForRelatedName = this.options.filename;
-
-      const index = filenameForRelatedName.lastIndexOf('?');
-
-      if (index >= 0) {
-        filenameForRelatedName = filenameForRelatedName.substr(0, index);
-      }
-
-      relatedName = `${path.extname(filenameForRelatedName).slice(1)}ed`;
-    } else {
-      relatedName = `${this.options.algorithm}ed`;
-    }
-
-    if (assetInfo.related && assetInfo.related[relatedName]) {
-      yield false;
+    if (assetNames.length === 0) {
+      return Promise.resolve();
     }
 
-    let input = assetSource.source();
-
-    if (!Buffer.isBuffer(input)) {
-      input = Buffer.from(input);
-    }
+    const scheduledTasks = [];
+    const cache = new CacheEngine(
+      compilation,
+      { cache: this.options.cache },
+      weakCache
+    );
 
-    if (input.length < this.options.threshold) {
-      yield false;
-    }
+    for (const assetName of assetNames) {
+      scheduledTasks.push(
+        (async () => {
+          const { source, info } = CompressionPlugin.getAsset(
+            compilation,
+            assetName
+          );
 
-    const task = { assetName, assetSource, assetInfo, input, relatedName };
+          if (info.compressed) {
+            return;
+          }
 
-    if (CompressionPlugin.isWebpack4()) {
-      task.cacheKeys = {
-        nodeVersion: process.version,
-        // eslint-disable-next-line global-require
-        'compression-webpack-plugin': require('../package.json').version,
-        algorithm: this.algorithm,
-        originalAlgorithm: this.options.algorithm,
-        compressionOptions: this.compressionOptions,
-        assetName,
-        contentHash: crypto.createHash('md4').update(input).digest('hex'),
-      };
-    }
+          let relatedName;
 
-    yield task;
-  }
+          if (typeof this.options.algorithm === 'function') {
+            let filenameForRelatedName = this.options.filename;
 
-  afterTask(compilation, task) {
-    const { output, input } = task;
+            const index = filenameForRelatedName.lastIndexOf('?');
 
-    if (output.source().length / input.length > this.options.minRatio) {
-      return;
-    }
+            if (index >= 0) {
+              filenameForRelatedName = filenameForRelatedName.substr(0, index);
+            }
 
-    const { assetSource, assetName } = task;
-    const newAssetName = CompressionPlugin.interpolateName(
-      assetName,
-      this.options.filename
-    );
+            relatedName = `${path.extname(filenameForRelatedName).slice(1)}ed`;
+          } else {
+            relatedName = `${this.options.algorithm}ed`;
+          }
 
-    CompressionPlugin.emitAsset(compilation, newAssetName, output, {
-      compressed: true,
-    });
+          if (info.related && info.related[relatedName]) {
+            return;
+          }
 
-    if (this.options.deleteOriginalAssets) {
-      // eslint-disable-next-line no-param-reassign
-      CompressionPlugin.deleteAsset(compilation, assetName);
-    } else {
-      CompressionPlugin.updateAsset(compilation, assetName, assetSource, {
-        related: { [task.relatedName]: newAssetName },
-      });
-    }
-  }
+          let input = source.source();
 
-  async runTasks(compilation, assetNames, CacheEngine, weakCache) {
-    const scheduledTasks = [];
-    const cache = new CacheEngine(
-      compilation,
-      {
-        cache: this.options.cache,
-      },
-      weakCache
-    );
+          if (!Buffer.isBuffer(input)) {
+            input = Buffer.from(input);
+          }
 
-    for (const assetName of assetNames) {
-      scheduledTasks.push(
-        (async () => {
-          const task = this.getTask(compilation, assetName).next().value;
+          if (input.length < this.options.threshold) {
+            return;
+          }
 
-          if (!task) {
-            return Promise.resolve();
+          const cacheData = { source };
+
+          if (CompressionPlugin.isWebpack4()) {
+            cacheData.cacheKeys = {
+              nodeVersion: process.version,
+              // eslint-disable-next-line global-require
+              'compression-webpack-plugin': require('../package.json').version,
+              algorithm: this.algorithm,
+              originalAlgorithm: this.options.algorithm,
+              compressionOptions: this.compressionOptions,
+              assetName,
+              contentHash: crypto.createHash('md4').update(input).digest('hex'),
+            };
+          } else {
+            cacheData.assetName = assetName;
           }
 
-          task.output = await cache.get(task, { RawSource });
+          let output = await cache.get(cacheData, { RawSource });
 
-          if (!task.output) {
+          if (!output) {
             try {
-              // eslint-disable-next-line no-param-reassign
-              task.output = new RawSource(await this.compress(task.input));
+              output = new RawSource(await this.runCompressionAlgorithm(input));
             } catch (error) {
               compilation.errors.push(error);
 
-              return Promise.resolve();
+              return;
             }
 
-            await cache.store(task);
+            cacheData.output = output;
+
+            await cache.store(cacheData);
           }
 
-          this.afterTask(compilation, task);
+          if (output.source().length / input.length > this.options.minRatio) {
+            return;
+          }
 
-          return Promise.resolve();
+          const newAssetName = CompressionPlugin.interpolateName(
+            assetName,
+            this.options.filename
+          );
+
+          CompressionPlugin.emitAsset(compilation, newAssetName, output, {
+            compressed: true,
+          });
+
+          if (this.options.deleteOriginalAssets) {
+            // eslint-disable-next-line no-param-reassign
+            CompressionPlugin.deleteAsset(compilation, assetName);
+          } else {
+            CompressionPlugin.updateAsset(compilation, assetName, source, {
+              related: { [relatedName]: newAssetName },
+            });
+          }
         })()
       );
     }
@@ -291,29 +284,6 @@ class CompressionPlugin {
 
   apply(compiler) {
     const pluginName = this.constructor.name;
-    const matchObject = ModuleFilenameHelpers.matchObject.bind(
-      // eslint-disable-next-line no-undefined
-      undefined,
-      this.options
-    );
-    const compressionFn = async (
-      compilation,
-      assets,
-      CacheEngine,
-      weakCache
-    ) => {
-      const assetNames = Object.keys(
-        typeof assets === 'undefined' ? compilation.assets : assets
-      ).filter((assetName) => matchObject(assetName));
-
-      if (assetNames.length === 0) {
-        return Promise.resolve();
-      }
-
-      await this.runTasks(compilation, assetNames, CacheEngine, weakCache);
-
-      return Promise.resolve();
-    };
 
     if (CompressionPlugin.isWebpack4()) {
       // eslint-disable-next-line global-require
@@ -322,7 +292,7 @@ class CompressionPlugin {
 
       compiler.hooks.emit.tapPromise({ name: pluginName }, (compilation) =>
         // eslint-disable-next-line no-undefined
-        compressionFn(compilation, undefined, CacheEngine, weakCache)
+        this.compress(compilation, undefined, CacheEngine, weakCache)
       );
     } else {
       // eslint-disable-next-line global-require
@@ -337,7 +307,7 @@ class CompressionPlugin {
             name: pluginName,
             stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER,
           },
-          (assets) => compressionFn(compilation, assets, CacheEngine)
+          (assets) => this.compress(compilation, assets, CacheEngine)
         );
 
         compilation.hooks.statsPrinter.tap(pluginName, (stats) => {


Test patch:
diff --git a/test/cache-option.test.js b/test/cache-option.test.js
index c323e3d..a85c87c 100644
--- a/test/cache-option.test.js
+++ b/test/cache-option.test.js
@@ -36,7 +36,7 @@ if (getCompiler.isWebpack4()) {
       ]);
     });
 
-    afterEach(() => {
+    afterAll(() => {
       return Promise.all([
         cacache.rm.all(falseCacheDirectory),
         cacache.rm.all(cacheDir),