Repository: webpack-contrib/copy-webpack-plugin
Pull request #467 (2020-05-12 16:39:15)

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


codecov[bot]: # [Codecov](https://codecov.io/gh/webpack-contrib/copy-webpack-plugin/pull/467?src=pr&el=h1) Report
> Merging [#467](https://codecov.io/gh/webpack-contrib/copy-webpack-plugin/pull/467?src=pr&el=desc) into [master](https://codecov.io/gh/webpack-contrib/copy-webpack-plugin/commit/c176d7d124cf3c5ad372576d4b0f7fbf5e1d0afc&el=desc) will **not change** coverage.
> The diff coverage is `n/a`.

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

```diff
@@           Coverage Diff           @@
##           master     #467   +/-   ##
=======================================
  Coverage   93.39%   93.39%           
=======================================
  Files           8        8           
  Lines         212      212           
  Branches       56       56           
=======================================
  Hits          198      198           
  Misses         13       13           
  Partials        1        1           
```



------

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


Patch:
diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml
index 03e3c27..b9a0324 100644
--- a/.github/workflows/nodejs.yml
+++ b/.github/workflows/nodejs.yml
@@ -43,8 +43,8 @@ jobs:
       - name: Lint
         run: npm run lint
 
-      - name: Security audit
-        run: npm run security
+      #      - name: Security audit
+      #        run: npm run security
 
       - name: Check commit message
         uses: wagoid/commitlint-github-action@v1
diff --git a/README.md b/README.md
index 970d250..5a4edbd 100644
--- a/README.md
+++ b/README.md
@@ -288,8 +288,8 @@ We try to automatically determine the `type` so you most likely do not need this
 
 |       Name       |    Type    |   Default   | Description                                                                                        |
 | :--------------: | :--------: | :---------: | :------------------------------------------------------------------------------------------------- |
-|   **`'dir'`**    | `{String}` | `undefined` | If `from` is directory, `to` has no extension or ends in `'/'`                                     |
-|   **`'file'`**   | `{String}` | `undefined` | If `to` has extension or `from` is file                                                            |
+|   **`'dir'`**    | `{String}` | `undefined` | If `to` has no extension or ends on `'/'`                                                          |
+|   **`'file'`**   | `{String}` | `undefined` | If `to` is not a directory and is not a template                                                   |
 | **`'template'`** | `{String}` | `undefined` | If `to` contains [a template pattern](https://github.com/webpack-contrib/file-loader#placeholders) |
 
 ##### `'dir'`
diff --git a/package.json b/package.json
index b7c1a46..fad4cea 100644
--- a/package.json
+++ b/package.json
@@ -49,7 +49,8 @@
     "normalize-path": "^3.0.0",
     "p-limit": "^2.3.0",
     "schema-utils": "^2.6.6",
-    "serialize-javascript": "^3.0.0"
+    "serialize-javascript": "^3.0.0",
+    "webpack-sources": "^1.4.3"
   },
   "devDependencies": {
     "@babel/cli": "^7.8.4",
diff --git a/src/postProcessPattern.js b/src/postProcessPattern.js
index 8e093fb..02c4281 100644
--- a/src/postProcessPattern.js
+++ b/src/postProcessPattern.js
@@ -8,6 +8,8 @@ import serialize from 'serialize-javascript';
 import findCacheDir from 'find-cache-dir';
 import normalizePath from 'normalize-path';
 
+import { RawSource } from 'webpack-sources';
+
 import { name, version } from '../package.json';
 
 import { stat, readFile } from './utils/promisify';
@@ -137,9 +139,28 @@ export default async function postProcessPattern(globalRef, pattern, file) {
 
   const targetPath = normalizePath(file.webpackTo);
 
-  if (compilation.assets[targetPath] && !file.force) {
-    logger.log(`skipping '${file.webpackTo}', because it already exists`);
+  const source = new RawSource(content);
+
+  const hasAssetsAPI = typeof compilation.emitAsset === 'function';
 
+  // For old version webpack 4
+  if (!hasAssetsAPI) {
+    compilation.assets[targetPath] = source;
+
+    return;
+  }
+
+  if (compilation.getAsset(targetPath)) {
+    if (file.force) {
+      logger.log(
+        `force updating '${file.webpackTo}' to compilation assets from '${file.absoluteFrom}'`
+      );
+
+      compilation.updateAsset(targetPath, source);
+      return;
+    }
+
+    logger.log(`skipping '${file.webpackTo}', because it already exists`);
     return;
   }
 
@@ -147,12 +168,5 @@ export default async function postProcessPattern(globalRef, pattern, file) {
     `writing '${file.webpackTo}' to compilation assets from '${file.absoluteFrom}'`
   );
 
-  compilation.assets[targetPath] = {
-    size() {
-      return stats.size;
-    },
-    source() {
-      return content;
-    },
-  };
+  compilation.emitAsset(targetPath, source);
 }


Test patch:
diff --git a/test/cacheTransform-option.test.js b/test/cacheTransform-option.test.js
index 62aad97..5b66974 100644
--- a/test/cacheTransform-option.test.js
+++ b/test/cacheTransform-option.test.js
@@ -247,4 +247,49 @@ describe('cache option', () => {
       .then(done)
       .catch(done);
   });
+
+  it('should cache when "from" is a file', (done) => {
+    const from = 'file.txt';
+
+    runEmit({
+      expectedAssetKeys: ['subdir/test.txt'],
+      expectedAssetContent: {
+        'subdir/test.txt': 'newchanged!',
+      },
+      patterns: [
+        {
+          from,
+          cacheTransform: true,
+          transform: function transform(content) {
+            return new Promise((resolve) => {
+              resolve(`${content}changed!`);
+            });
+          },
+          transformPath(targetPath, absoluteFrom) {
+            expect(absoluteFrom).toBe(path.join(FIXTURES_DIR, 'file.txt'));
+
+            return targetPath.replace('file.txt', 'subdir/test.txt');
+          },
+        },
+      ],
+    })
+      .then(() =>
+        cacache.ls(cacheDir).then((cacheEntries) => {
+          const cacheKeys = Object.keys(cacheEntries);
+
+          expect(cacheKeys).toHaveLength(1);
+
+          cacheKeys.forEach((cacheKey) => {
+            // eslint-disable-next-line no-new-func
+            const cacheEntry = new Function(
+              `'use strict'\nreturn ${cacheKey}`
+            )();
+
+            expect(cacheEntry.pattern.from).toBe(from);
+          });
+        })
+      )
+      .then(done)
+      .catch(done);
+  });
 });
diff --git a/test/transform-option.test.js b/test/transform-option.test.js
index ce47a9d..f1f9882 100644
--- a/test/transform-option.test.js
+++ b/test/transform-option.test.js
@@ -1,6 +1,7 @@
 import path from 'path';
+import zlib from 'zlib';
 
-import { runEmit } from './helpers/run';
+import { run, runEmit } from './helpers/run';
 
 const FIXTURES_DIR = path.join(__dirname, 'fixtures');
 
@@ -181,4 +182,53 @@ describe('transform option', () => {
       .then(done)
       .catch(done);
   });
+
+  it('should be a different size for the source file and the converted file', (done) => {
+    run({
+      patterns: [
+        {
+          from: 'file.txt',
+        },
+        {
+          from: 'file.txt',
+          to: 'file.txt.gz',
+          transform: (content) => zlib.gzipSync(content),
+        },
+      ],
+    })
+      .then(({ compilation }) => {
+        expect(
+          compilation.assets['file.txt'].size() !==
+            compilation.assets['file.txt.gz'].size()
+        ).toBe(true);
+      })
+      .then(done)
+      .catch(done);
+  });
+
+  it('should transform file when "from" is a file', (done) => {
+    runEmit({
+      expectedAssetKeys: ['subdir/test.txt'],
+      expectedAssetContent: {
+        'subdir/test.txt': 'newchanged',
+      },
+      patterns: [
+        {
+          from: 'file.txt',
+          transform(content, absoluteFrom) {
+            expect(absoluteFrom.includes(FIXTURES_DIR)).toBe(true);
+
+            return `${content}changed`;
+          },
+          transformPath(targetPath, absoluteFrom) {
+            expect(absoluteFrom).toBe(path.join(FIXTURES_DIR, 'file.txt'));
+
+            return targetPath.replace('file.txt', 'subdir/test.txt');
+          },
+        },
+      ],
+    })
+      .then(done)
+      .catch(done);
+  });
 });