Repository: webpack-contrib/copy-webpack-plugin
Pull request #459 (2020-05-07 15:06:52)

chore: refactor logger
<!--
  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**
- [x] **test update** <!-- if bug or feature is checked, this should be too -->
- [ ] **typo fix**
- [ ] **metadata update**

### Motivation / Use-Case

Refactor logger

### Breaking Changes

No

### Additional Info

No


codecov[bot]: # [Codecov](https://codecov.io/gh/webpack-contrib/copy-webpack-plugin/pull/459?src=pr&el=h1) Report
> Merging [#459](https://codecov.io/gh/webpack-contrib/copy-webpack-plugin/pull/459?src=pr&el=desc) into [master](https://codecov.io/gh/webpack-contrib/copy-webpack-plugin/commit/1e2f3a169745b42c6c8584e86c64bacf24077976&el=desc) will **decrease** coverage by `0.73%`.
> The diff coverage is `100.00%`.

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

```diff
@@            Coverage Diff             @@
##           master     #459      +/-   ##
==========================================
- Coverage   94.71%   93.97%   -0.74%     
==========================================
  Files           9        9              
  Lines         246      249       +3     
  Branches       63       63              
==========================================
+ Hits          233      234       +1     
- Misses         12       14       +2     
  Partials        1        1              
```


| [Impacted Files](https://codecov.io/gh/webpack-contrib/copy-webpack-plugin/pull/459?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [src/index.js](https://codecov.io/gh/webpack-contrib/copy-webpack-plugin/pull/459/diff?src=pr&el=tree#diff-c3JjL2luZGV4Lmpz) | `95.12% <100.00%> (-4.88%)` | :arrow_down: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/webpack-contrib/copy-webpack-plugin/pull/459?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/copy-webpack-plugin/pull/459?src=pr&el=footer). Last update [1e2f3a1...eceb2cf](https://codecov.io/gh/webpack-contrib/copy-webpack-plugin/pull/459?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).


Patch:
diff --git a/src/index.js b/src/index.js
index 5a0ab85..5fa3e22 100644
--- a/src/index.js
+++ b/src/index.js
@@ -17,81 +17,59 @@ class CopyPlugin {
   }
 
   apply(compiler) {
-    const fileDependencies = new Set();
-    const contextDependencies = new Set();
     const plugin = { name: 'CopyPlugin' };
-    const logger = compiler.getInfrastructureLogger('copy-webpack-plugin');
 
-    compiler.hooks.emit.tapAsync(plugin, (compilation, callback) => {
-      logger.debug('starting emit');
+    compiler.hooks.compilation.tap(plugin, (compilation) => {
+      const logger = compilation.getLogger('copy-webpack-plugin');
 
-      const globalRef = {
-        context: compiler.options.context,
-        logger,
-        compilation,
-        fileDependencies,
-        contextDependencies,
-        inputFileSystem: compiler.inputFileSystem,
-        output: compiler.options.output.path,
-        ignore: this.options.ignore || [],
-        concurrency: this.options.concurrency,
-      };
+      compilation.hooks.additionalAssets.tapAsync(
+        'copy-webpack-plugin',
+        (callback) => {
+          logger.debug('start to adding additionalAssets');
 
-      Promise.all(
-        this.patterns.map((pattern) =>
-          Promise.resolve()
-            .then(() => preProcessPattern(globalRef, pattern))
-            // Every source (from) is assumed to exist here
-            // eslint-disable-next-line no-shadow
-            .then((pattern) =>
-              processPattern(globalRef, pattern).then((files) => {
-                if (!files) {
-                  return Promise.resolve();
-                }
+          const globalRef = {
+            context: compiler.options.context,
+            logger,
+            compilation,
+            inputFileSystem: compiler.inputFileSystem,
+            output: compiler.options.output.path,
+            ignore: this.options.ignore || [],
+            concurrency: this.options.concurrency,
+          };
 
-                return Promise.all(
-                  files
-                    .filter(Boolean)
-                    .map((file) => postProcessPattern(globalRef, pattern, file))
-                );
-              })
-            )
-        )
-      )
-        .catch((error) => {
-          compilation.errors.push(error);
-        })
-        .then(() => {
-          logger.debug('finishing emit');
-
-          callback();
-        });
-    });
-
-    compiler.hooks.afterEmit.tapAsync(plugin, (compilation, callback) => {
-      logger.debug('starting after-emit');
+          Promise.all(
+            this.patterns.map((pattern) =>
+              Promise.resolve()
+                .then(() => preProcessPattern(globalRef, pattern))
+                // Every source (from) is assumed to exist here
+                // eslint-disable-next-line no-shadow
+                .then((pattern) =>
+                  processPattern(globalRef, pattern).then((files) => {
+                    if (!files) {
+                      return Promise.resolve();
+                    }
 
-      // Add file dependencies
-      if ('addAll' in compilation.fileDependencies) {
-        compilation.fileDependencies.addAll(fileDependencies);
-      } else {
-        for (const fileDependency of fileDependencies) {
-          compilation.fileDependencies.add(fileDependency);
-        }
-      }
+                    return Promise.all(
+                      files
+                        .filter(Boolean)
+                        .map((file) =>
+                          postProcessPattern(globalRef, pattern, file)
+                        )
+                    );
+                  })
+                )
+            )
+          )
+            .catch((error) => {
+              compilation.errors.push(error);
+            })
+            .then(() => {
+              logger.debug('end to adding additionalAssets');
 
-      // Add context dependencies
-      if ('addAll' in compilation.contextDependencies) {
-        compilation.contextDependencies.addAll(contextDependencies);
-      } else {
-        for (const contextDependency of contextDependencies) {
-          compilation.contextDependencies.add(contextDependency);
+              callback();
+            });
         }
-      }
-
-      logger.debug('finishing after-emit');
-
-      callback();
+      );
     });
   }
 }
diff --git a/src/postProcessPattern.js b/src/postProcessPattern.js
index 6cbc060..dbf0944 100644
--- a/src/postProcessPattern.js
+++ b/src/postProcessPattern.js
@@ -15,7 +15,7 @@ import { stat, readFile } from './utils/promisify';
 /* eslint-disable no-param-reassign */
 
 export default function postProcessPattern(globalRef, pattern, file) {
-  const { logger, compilation, fileDependencies, inputFileSystem } = globalRef;
+  const { logger, compilation, inputFileSystem } = globalRef;
 
   logger.debug(`getting stats for '${file.absoluteFrom}' to write to assets`);
 
@@ -35,7 +35,8 @@ export default function postProcessPattern(globalRef, pattern, file) {
 
     // If this came from a glob, add it to the file watchlist
     if (pattern.fromType === 'glob') {
-      fileDependencies.add(file.absoluteFrom);
+      logger.debug(`add ${file.absoluteFrom} as fileDependencies`);
+      compilation.fileDependencies.add(file.absoluteFrom);
     }
 
     logger.debug(`reading '${file.absoluteFrom}' to write to assets`);
diff --git a/src/utils/createPatternGlob.js b/src/utils/createPatternGlob.js
index 4a3fbdc..7403569 100644
--- a/src/utils/createPatternGlob.js
+++ b/src/utils/createPatternGlob.js
@@ -16,7 +16,7 @@ function getAbsoluteContext(context) {
 }
 
 function createPatternGlob(pattern, globalRef) {
-  const { logger, fileDependencies, contextDependencies } = globalRef;
+  const { logger, compilation } = globalRef;
 
   pattern.globOptions = Object.assign(
     {
@@ -29,7 +29,8 @@ function createPatternGlob(pattern, globalRef) {
   switch (pattern.fromType) {
     case 'dir':
       logger.debug(`determined '${pattern.absoluteFrom}' is a directory`);
-      contextDependencies.add(pattern.absoluteFrom);
+      logger.debug(`add ${pattern.absoluteFrom} as contextDependencies`);
+      compilation.contextDependencies.add(pattern.absoluteFrom);
 
       pattern.context = pattern.absoluteFrom;
       pattern.glob = path.posix.join(
@@ -44,7 +45,8 @@ function createPatternGlob(pattern, globalRef) {
 
     case 'file':
       logger.debug(`determined '${pattern.absoluteFrom}' is a file`);
-      fileDependencies.add(pattern.absoluteFrom);
+      logger.debug(`add ${pattern.absoluteFrom} as fileDependencies`);
+      compilation.fileDependencies.add(pattern.absoluteFrom);
 
       pattern.context = path.dirname(pattern.absoluteFrom);
       pattern.glob = getAbsoluteContext(pattern.absoluteFrom);
@@ -55,7 +57,14 @@ function createPatternGlob(pattern, globalRef) {
 
     default:
       logger.debug(`determined '${pattern.absoluteFrom}' is a glob`);
-      contextDependencies.add(path.normalize(globParent(pattern.absoluteFrom)));
+
+      // eslint-disable-next-line no-case-declarations
+      const contextDependencies = path.normalize(
+        globParent(pattern.absoluteFrom)
+      );
+
+      logger.debug(`add ${contextDependencies} as contextDependencies`);
+      compilation.contextDependencies.add(contextDependencies);
 
       pattern.fromType = 'glob';
       pattern.globOptions = pattern.globOptions || {};


Test patch:
diff --git a/test/CopyPlugin.test.js b/test/CopyPlugin.test.js
index d07e5cd..bb6eded 100644
--- a/test/CopyPlugin.test.js
+++ b/test/CopyPlugin.test.js
@@ -539,3 +539,32 @@ describe('apply function', () => {
     });
   });
 });
+
+describe('logging', () => {
+  it('should logging', (done) => {
+    const expectedAssetKeys = ['file.txt'];
+
+    run({
+      patterns: [
+        {
+          from: 'file.txt',
+        },
+      ],
+    })
+      .then(({ compiler, stats }) => {
+        const root = path.resolve(__dirname).replace(/\\/g, '/');
+        const logs = stats.compilation.logging
+          .get('copy-webpack-plugin')
+          .map((entry) =>
+            entry.args[0].replace(/\\/g, '/').split(root).join('.')
+          );
+
+        expect(
+          Array.from(Object.keys(readAssets(compiler, stats))).sort()
+        ).toEqual(expectedAssetKeys);
+        expect({ result: logs }).toMatchSnapshot({ result: logs });
+      })
+      .then(done)
+      .catch(done);
+  });
+});
diff --git a/test/__snapshots__/CopyPlugin.test.js.snap b/test/__snapshots__/CopyPlugin.test.js.snap
new file mode 100644
index 0000000..71946eb
--- /dev/null
+++ b/test/__snapshots__/CopyPlugin.test.js.snap
@@ -0,0 +1,28 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`logging should logging 1`] = `
+Object {
+  "result": Array [
+    "start to adding additionalAssets",
+    "processing from: 'file.txt' to: '.'",
+    "getting stats for './fixtures/file.txt' to determinate 'fromType'",
+    "determined './fixtures/file.txt' is a file",
+    "add ./fixtures/file.txt as fileDependencies",
+    "begin globbing './fixtures/file.txt' with a context of './fixtures'",
+    "found ./fixtures/file.txt",
+    "testing watch/**/* against file.txt",
+    "watch/**/* doesn't match file.txt",
+    "testing directory-ln against file.txt",
+    "directory-ln doesn't match file.txt",
+    "testing file-ln.txt against file.txt",
+    "file-ln.txt doesn't match file.txt",
+    "testing symlink/**/* against file.txt",
+    "symlink/**/* doesn't match file.txt",
+    "determined that './fixtures/file.txt' should write to 'file.txt'",
+    "getting stats for './fixtures/file.txt' to write to assets",
+    "reading './fixtures/file.txt' to write to assets",
+    "writing 'file.txt' to compilation assets from './fixtures/file.txt'",
+    "end to adding additionalAssets",
+  ],
+}
+`;
diff --git a/test/helpers/PreCopyPlugin.js b/test/helpers/PreCopyPlugin.js
index 40951d5..df020c2 100644
--- a/test/helpers/PreCopyPlugin.js
+++ b/test/helpers/PreCopyPlugin.js
@@ -6,17 +6,22 @@ class PreCopyPlugin {
   apply(compiler) {
     const plugin = { name: 'PreCopyPlugin' };
 
-    compiler.hooks.emit.tapAsync(plugin, (compilation, callback) => {
-      this.options.existingAssets.forEach((assetName) => {
-        // eslint-disable-next-line no-param-reassign
-        compilation.assets[assetName] = {
-          source() {
-            return 'existing';
-          },
-        };
-      });
+    compiler.hooks.compilation.tap(plugin, (compilation) => {
+      compilation.hooks.additionalAssets.tapAsync(
+        'copy-webpack-plugin',
+        (callback) => {
+          this.options.existingAssets.forEach((assetName) => {
+            // eslint-disable-next-line no-param-reassign
+            compilation.assets[assetName] = {
+              source() {
+                return 'existing';
+              },
+            };
+          });
 
-      callback();
+          callback();
+        }
+      );
     });
   }
 }