Skip to content

Commit

Permalink
fix(removeComments): preserve copyright and licensing and add param
Browse files Browse the repository at this point in the history
  • Loading branch information
SethFalco committed Oct 22, 2023
1 parent e529c66 commit d09612d
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 4 deletions.
4 changes: 3 additions & 1 deletion plugins/plugins-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,9 @@ type DefaultPlugins = {

moveElemsAttrsToGroup: void;
moveGroupAttrsToElems: void;
removeComments: void;
removeComments: {
preservePatterns: Array<RegExp|string> | false
};
removeDesc: {
removeAny?: boolean;
};
Expand Down
33 changes: 30 additions & 3 deletions plugins/removeComments.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,17 @@ 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,
/creativecommons/i,
];

/**
* Remove comments.
*
Expand All @@ -16,13 +27,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);
},
},
};
Expand Down
2 changes: 2 additions & 0 deletions test/plugins/removeComments.02.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
15 changes: 15 additions & 0 deletions test/plugins/removeComments.03.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit d09612d

Please sign in to comment.