From 499c07b27ad9ad94662fdd163d459c89632146da Mon Sep 17 00:00:00 2001 From: Seth Falco Date: Sun, 22 Oct 2023 10:33:11 +0100 Subject: [PATCH] fix(removeComments): preserve copyright and licensing and add param --- plugins/plugins-types.ts | 4 +++- plugins/removeComments.js | 28 +++++++++++++++++++++++++--- test/plugins/removeComments.02.svg | 2 ++ test/plugins/removeComments.03.svg | 15 +++++++++++++++ 4 files changed, 45 insertions(+), 4 deletions(-) create mode 100644 test/plugins/removeComments.03.svg diff --git a/plugins/plugins-types.ts b/plugins/plugins-types.ts index a4cca210b..849f17e0f 100644 --- a/plugins/plugins-types.ts +++ b/plugins/plugins-types.ts @@ -119,7 +119,9 @@ type DefaultPlugins = { moveElemsAttrsToGroup: void; moveGroupAttrsToElems: void; - removeComments: void; + removeComments: { + preservePatterns: Array | false + }; removeDesc: { removeAny?: boolean; }; diff --git a/plugins/removeComments.js b/plugins/removeComments.js index 70e462714..d985d0f5c 100644 --- a/plugins/removeComments.js +++ b/plugins/removeComments.js @@ -5,6 +5,12 @@ const { detachNodeFromParent } = require('../lib/xast.js'); exports.name = 'removeComments'; exports.description = 'removes comments'; +/** + * If a comment matches one of the following patterns, it will be + * preserved by default. Particularly for copyright/license information. + */ +const DEFAULT_PRESERVE_PATTERNS = [/^!/, /LICENSE/i, /COPYRIGHT/i]; + /** * Remove comments. * @@ -16,13 +22,29 @@ exports.description = 'removes comments'; * * @type {import('./plugins-types').Plugin<'removeComments'>} */ -exports.fn = () => { +exports.fn = (_root, params) => { + const { preservePatterns = DEFAULT_PRESERVE_PATTERNS } = params; + return { comment: { enter: (node, parentNode) => { - if (node.value.charAt(0) !== '!') { - detachNodeFromParent(node, parentNode); + if (preservePatterns) { + if (!Array.isArray(preservePatterns)) { + throw Error( + `Expected array in removeComments preservePatterns parameter but received ${preservePatterns}` + ); + } + + const matches = preservePatterns.some((pattern) => { + return new RegExp(pattern).test(node.value); + }); + + if (matches) { + return; + } } + + detachNodeFromParent(node, parentNode); }, }, }; diff --git a/test/plugins/removeComments.02.svg b/test/plugins/removeComments.02.svg index d62ff2a27..ef594f560 100644 --- a/test/plugins/removeComments.02.svg +++ b/test/plugins/removeComments.02.svg @@ -1,5 +1,6 @@ + test @@ -7,5 +8,6 @@ + test diff --git a/test/plugins/removeComments.03.svg b/test/plugins/removeComments.03.svg new file mode 100644 index 000000000..339808547 --- /dev/null +++ b/test/plugins/removeComments.03.svg @@ -0,0 +1,15 @@ + + + + test + + +@@@ + + + test + + +@@@ + +{"preservePatterns":false}