Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix printf-like formatting for custom messages #6389

Merged
merged 1 commit into from Oct 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/strong-lions-listen.md
@@ -0,0 +1,5 @@
---
"stylelint": patch
---

Fixed: `printf`-like formatting for custom messages
2 changes: 1 addition & 1 deletion lib/utils/__tests__/report.test.js
Expand Up @@ -260,7 +260,7 @@ test('with custom message', () => {
},
},
message: 'bar',
messageArgs: ['str', true, 10, /regex/],
messageArgs: ['str', true, 10, /regex/, 'should_be_ignored'],
node: {
rangeBy: defaultRangeBy,
},
Expand Down
15 changes: 12 additions & 3 deletions lib/utils/report.js
@@ -1,7 +1,5 @@
'use strict';

const util = require('util');

/**
* Report a problem.
*
Expand Down Expand Up @@ -124,8 +122,19 @@ function buildWarningMessage(message, messageArgs) {
const args = messageArgs || [];

if (typeof message === 'string') {
return util.format(message, ...args);
return printfLike(message, ...args);
}

return message(...args);
}

/**
* @param {string} format
* @param {Array<unknown>} args
* @returns {string}
*/
function printfLike(format, ...args) {
return args.reduce((/** @type {string} */ result, arg) => {
return result.replace(/%[ds]/, String(arg));
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[note] For now, only %s and %d support seems enough.

}, format);
}