Repository: webpack-contrib/copy-webpack-plugin
Pull request #472 (2020-05-14 17:06:03)

chore: drop test option in favor transformPath
<!--
  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**
- [x] **test update** <!-- if bug or feature is checked, this should be too -->
- [ ] **typo fix**
- [x] **metadata update**

### Motivation / Use-Case

Drop `test` option in favor `transformPath` option

### Breaking Changes

Yes

### Additional Info

No


codecov[bot]: # [Codecov](https://codecov.io/gh/webpack-contrib/copy-webpack-plugin/pull/472?src=pr&el=h1) Report
> Merging [#472](https://codecov.io/gh/webpack-contrib/copy-webpack-plugin/pull/472?src=pr&el=desc) into [master](https://codecov.io/gh/webpack-contrib/copy-webpack-plugin/commit/045f629808c976bff0e8d121db05244cb40524c6&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/472/graphs/tree.svg?width=650&height=150&src=pr&token=fEoU9iBFGL)](https://codecov.io/gh/webpack-contrib/copy-webpack-plugin/pull/472?src=pr&el=tree)

```diff
@@           Coverage Diff           @@
##           master     #472   +/-   ##
=======================================
  Coverage   94.85%   94.85%           
=======================================
  Files           8        8           
  Lines         214      214           
  Branches       56       56           
=======================================
  Hits          203      203           
  Misses         11       11           
```



------

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


Patch:
diff --git a/README.md b/README.md
index e002e37..673d05e 100644
--- a/README.md
+++ b/README.md
@@ -81,7 +81,6 @@ module.exports = {
 |        [`context`](#context)        |     `{String}`      | `options.context \|\| compiler.options.context` | A path that determines how to interpret the `from` path.                                              |
 |    [`globOptions`](#globoptions)    |     `{Object}`      |                   `undefined`                   | [Options][glob-options] passed to the glob pattern matching library including `ignore` option.        |
 |         [`toType`](#totype)         |     `{String}`      |                   `undefined`                   | Determinate what is `to` option - directory, file or template.                                        |
-|           [`test`](#test)           | `{String\|RegExp}`  |                   `undefined`                   | Pattern for extracting elements to be used in `to` templates.                                         |
 |          [`force`](#force)          |     `{Boolean}`     |                     `false`                     | Overwrites files already in `compilation.assets` (usually added by other plugins/loaders).            |
 |        [`flatten`](#flatten)        |     `{Boolean}`     |                     `false`                     | Removes all directory references and only copies file names.                                          |
 |      [`transform`](#transform)      |    `{Function}`     |                   `undefined`                   | Allows to modify the file contents.                                                                   |
@@ -353,37 +352,6 @@ module.exports = {
 };
 ```
 
-#### `test`
-
-Type: `string|RegExp`
-Default: `undefined`
-
-Pattern for extracting elements to be used in `to` templates.
-
-Defines a `{RegExp}` to match some parts of the file path.
-These capture groups can be reused in the name property using `[N]` placeholder.
-Note that `[0]` will be replaced by the entire path of the file,
-whereas `[1]` will contain the first capturing parenthesis of your `{RegExp}`
-and so on...
-
-**webpack.config.js**
-
-```js
-module.exports = {
-  plugins: [
-    new CopyPlugin({
-      patterns: [
-        {
-          from: '*/*',
-          to: '[1]-[2].[hash].[ext]',
-          test: /([^/]+)\/(.+)\.png$/,
-        },
-      ],
-    }),
-  ],
-};
-```
-
 #### `force`
 
 Type: `Boolean`
diff --git a/src/options.json b/src/options.json
index 3409991..c16c726 100644
--- a/src/options.json
+++ b/src/options.json
@@ -16,16 +16,6 @@
         "toType": {
           "enum": ["dir", "file", "template"]
         },
-        "test": {
-          "anyOf": [
-            {
-              "type": "string"
-            },
-            {
-              "instanceof": "RegExp"
-            }
-          ]
-        },
         "force": {
           "type": "boolean"
         },
diff --git a/src/postProcessPattern.js b/src/postProcessPattern.js
index 02c4281..265f0b2 100644
--- a/src/postProcessPattern.js
+++ b/src/postProcessPattern.js
@@ -117,7 +117,6 @@ export default async function postProcessPattern(globalRef, pattern, file) {
       file.webpackTo,
       {
         content,
-        regExp: file.webpackToRegExp,
         context: pattern.context,
       }
     );
diff --git a/src/processPattern.js b/src/processPattern.js
index 631e5a0..9a6de04 100644
--- a/src/processPattern.js
+++ b/src/processPattern.js
@@ -56,7 +56,6 @@ export default async function processPattern(globalRef, pattern) {
       file.webpackTo = pattern.to || file.relativeFrom;
     } else if (pattern.toType === 'template') {
       file.webpackTo = pattern.to;
-      file.webpackToRegExp = pattern.test;
     }
 
     if (path.isAbsolute(file.webpackTo)) {


Test patch:
diff --git a/test/__snapshots__/validate-options.test.js.snap b/test/__snapshots__/validate-options.test.js.snap
index 4c895eb..e4d88ec 100644
--- a/test/__snapshots__/validate-options.test.js.snap
+++ b/test/__snapshots__/validate-options.test.js.snap
@@ -14,7 +14,7 @@ exports[`validate options should throw an error on the "options" option with "{"
 exports[`validate options should throw an error on the "patterns" option with "" value 1`] = `
 "Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
  - options.patterns should be an array:
-   [non-empty string | object { from, to?, context?, toType?, test?, force?, flatten?, transform?, cacheTransform?, transformPath?, … }, ...] (should not have fewer than 1 item)"
+   [non-empty string | object { from, to?, context?, toType?, force?, flatten?, transform?, cacheTransform?, transformPath?, … }, ...] (should not have fewer than 1 item)"
 `;
 
 exports[`validate options should throw an error on the "patterns" option with "[""]" value 1`] = `
@@ -42,18 +42,6 @@ exports[`validate options should throw an error on the "patterns" option with "[
  - options.patterns[0].force should be a boolean."
 `;
 
-exports[`validate options should throw an error on the "patterns" option with "[{"from":"test.txt","to":"dir","context":"context","test":true}]" value 1`] = `
-"Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
- - options.patterns[0] should be one of these:
-   non-empty string | object { from, to?, context?, toType?, test?, force?, flatten?, transform?, cacheTransform?, transformPath?, … }
-   Details:
-    * options.patterns[0].test should be one of these:
-      string | RegExp
-      Details:
-       * options.patterns[0].test should be a string.
-       * options.patterns[0].test should be an instance of RegExp."
-`;
-
 exports[`validate options should throw an error on the "patterns" option with "[{"from":"test.txt","to":"dir","context":"context","toType":"foo"}]" value 1`] = `
 "Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
  - options.patterns[0].toType should be one of these:
@@ -73,7 +61,7 @@ exports[`validate options should throw an error on the "patterns" option with "[
 exports[`validate options should throw an error on the "patterns" option with "[{"from":"test.txt","to":"dir","context":"context"}]" value 1`] = `
 "Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
  - options.patterns[0] should be one of these:
-   non-empty string | object { from, to?, context?, toType?, test?, force?, flatten?, transform?, cacheTransform?, transformPath?, … }
+   non-empty string | object { from, to?, context?, toType?, force?, flatten?, transform?, cacheTransform?, transformPath?, … }
    Details:
     * options.patterns[0].cacheTransform should be one of these:
       boolean | object { … }
@@ -112,19 +100,19 @@ exports[`validate options should throw an error on the "patterns" option with "[
 exports[`validate options should throw an error on the "patterns" option with "{}" value 1`] = `
 "Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
  - options.patterns should be an array:
-   [non-empty string | object { from, to?, context?, toType?, test?, force?, flatten?, transform?, cacheTransform?, transformPath?, … }, ...] (should not have fewer than 1 item)"
+   [non-empty string | object { from, to?, context?, toType?, force?, flatten?, transform?, cacheTransform?, transformPath?, … }, ...] (should not have fewer than 1 item)"
 `;
 
 exports[`validate options should throw an error on the "patterns" option with "true" value 1`] = `
 "Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
  - options.patterns should be an array:
-   [non-empty string | object { from, to?, context?, toType?, test?, force?, flatten?, transform?, cacheTransform?, transformPath?, … }, ...] (should not have fewer than 1 item)"
+   [non-empty string | object { from, to?, context?, toType?, force?, flatten?, transform?, cacheTransform?, transformPath?, … }, ...] (should not have fewer than 1 item)"
 `;
 
 exports[`validate options should throw an error on the "patterns" option with "true" value 2`] = `
 "Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
  - options.patterns should be an array:
-   [non-empty string | object { from, to?, context?, toType?, test?, force?, flatten?, transform?, cacheTransform?, transformPath?, … }, ...] (should not have fewer than 1 item)"
+   [non-empty string | object { from, to?, context?, toType?, force?, flatten?, transform?, cacheTransform?, transformPath?, … }, ...] (should not have fewer than 1 item)"
 `;
 
 exports[`validate options should throw an error on the "unknown" option with "/test/" value 1`] = `
diff --git a/test/test-option.test.js b/test/test-option.test.js
deleted file mode 100644
index e32b95d..0000000
--- a/test/test-option.test.js
+++ /dev/null
@@ -1,73 +0,0 @@
-import path from 'path';
-
-import { runEmit } from './helpers/run';
-
-describe('test option', () => {
-  it('should move files to a root directory with [1]', (done) => {
-    runEmit({
-      expectedAssetKeys: ['txt'],
-      patterns: [
-        {
-          from: 'directory/nested/deep-nested',
-          to: '[1]',
-          test: /\.([^.]*)$/,
-        },
-      ],
-    })
-      .then(done)
-      .catch(done);
-  });
-
-  it('should move files to a non-root directory with [1]', (done) => {
-    runEmit({
-      expectedAssetKeys: ['nested/txt'],
-      patterns: [
-        {
-          from: 'directory/nested/deep-nested',
-          to: 'nested/[1]',
-          test: /\.([^.]*)$/,
-        },
-      ],
-    })
-      .then(done)
-      .catch(done);
-  });
-
-  it('should move files and flatten them to a non-root directory with [1]-[2].[ext]', (done) => {
-    runEmit({
-      expectedAssetKeys: [
-        'nested/deep-nested-deepnested.txt',
-        'nested/directory-directoryfile.txt',
-        'nested/nested-nestedfile.txt',
-      ],
-      patterns: [
-        {
-          from: 'directory/**/*',
-          test: `([^\\${path.sep}]+)\\${path.sep}([^\\${path.sep}]+)\\.\\w+$`,
-          to: 'nested/[1]-[2].[ext]',
-        },
-      ],
-    })
-      .then(done)
-      .catch(done);
-  });
-
-  it('should move files and flatten them to a root directory with [1]-[2].[ext]', (done) => {
-    runEmit({
-      expectedAssetKeys: [
-        'deep-nested-deepnested.txt',
-        'directory-directoryfile.txt',
-        'nested-nestedfile.txt',
-      ],
-      patterns: [
-        {
-          from: 'directory/**/*',
-          test: `([^\\${path.sep}]+)\\${path.sep}([^\\${path.sep}]+)\\.\\w+$`,
-          to: '[1]-[2].[ext]',
-        },
-      ],
-    })
-      .then(done)
-      .catch(done);
-  });
-});
diff --git a/test/transformPath-option.test.js b/test/transformPath-option.test.js
index e9e6115..9d6e9c4 100644
--- a/test/transformPath-option.test.js
+++ b/test/transformPath-option.test.js
@@ -192,4 +192,82 @@ describe('transformPath option', () => {
       .then(done)
       .catch(done);
   });
+
+  it('should move files', (done) => {
+    runEmit({
+      expectedAssetKeys: ['txt'],
+      patterns: [
+        {
+          from: 'directory/nested/deep-nested',
+          to: '[1]',
+          transformPath(targetPath, absolutePath) {
+            const mathes = absolutePath.match(/\.([^.]*)$/);
+            const [, res] = mathes;
+            const target = targetPath.replace(/\[[1]\]/, res);
+
+            return target;
+          },
+        },
+      ],
+    })
+      .then(done)
+      .catch(done);
+  });
+
+  it('should move files to a non-root directory with [1]', (done) => {
+    runEmit({
+      expectedAssetKeys: ['nested/txt'],
+      patterns: [
+        {
+          from: 'directory/nested/deep-nested',
+          to: 'nested/[1]',
+          transformPath(targetPath, absolutePath) {
+            const mathes = absolutePath.match(/\.([^.]*)$/);
+            const [, res] = mathes;
+            const target = targetPath.replace(/\[[1]\]/, res);
+
+            return target;
+          },
+        },
+      ],
+    })
+      .then(done)
+      .catch(done);
+  });
+
+  it('should move files', (done) => {
+    runEmit({
+      expectedAssetKeys: [
+        'deep-nested-deepnested.txt',
+        'directoryfile.txt',
+        'nested-nestedfile.txt',
+      ],
+      patterns: [
+        {
+          from: '**/*',
+          context: 'directory',
+          transformPath(targetPath) {
+            const pathSegments = path.parse(targetPath);
+            const result = [];
+
+            if (pathSegments.root) {
+              result.push(pathSegments.root);
+            }
+
+            if (pathSegments.dir) {
+              result.push(pathSegments.dir.split(path.sep).pop());
+            }
+
+            if (pathSegments.base) {
+              result.push(pathSegments.base);
+            }
+
+            return result.join('-');
+          },
+        },
+      ],
+    })
+      .then(done)
+      .catch(done);
+  });
 });
diff --git a/test/validate-options.test.js b/test/validate-options.test.js
index 69dd911..ab5500e 100644
--- a/test/validate-options.test.js
+++ b/test/validate-options.test.js
@@ -53,7 +53,6 @@ describe('validate options', () => {
             to: 'dir',
             context: 'context',
             toType: 'file',
-            test: /test/,
             force: true,
             flatten: true,
             transform: () => {},
@@ -71,22 +70,6 @@ describe('validate options', () => {
             },
           },
         ],
-        [
-          {
-            from: 'test.txt',
-            to: 'dir',
-            context: 'context',
-            test: 'test',
-          },
-        ],
-        [
-          {
-            from: 'test.txt',
-            to: 'dir',
-            context: 'context',
-            test: /test/,
-          },
-        ],
         [
           {
             from: 'test.txt',
@@ -142,14 +125,6 @@ describe('validate options', () => {
             toType: 'foo',
           },
         ],
-        [
-          {
-            from: 'test.txt',
-            to: 'dir',
-            context: 'context',
-            test: true,
-          },
-        ],
         [
           {
             from: 'test.txt',