Skip to content

Commit

Permalink
Fix printf-like formatting for custom messages (#6389)
Browse files Browse the repository at this point in the history
The Node.js `util.format()` API can concatenate extra arguments to the result string.
This behavior is not suitable for custom messages.
So, this commit replace `util.format()` with our implementation.

See https://nodejs.org/api/util.html#utilformatformat-args

> If there are more arguments passed to the `util.format()` method than the number of specifiers,
> the extra arguments are concatenated to the returned string, separated by spaces:
  • Loading branch information
ybiquitous committed Oct 3, 2022
1 parent 751acda commit 6599729
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
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));
}, format);
}

0 comments on commit 6599729

Please sign in to comment.