From 659972918323c6a15015a16188d130d7f7700612 Mon Sep 17 00:00:00 2001 From: Masafumi Koba <473530+ybiquitous@users.noreply.github.com> Date: Mon, 3 Oct 2022 23:49:22 +0900 Subject: [PATCH] Fix `printf`-like formatting for custom messages (#6389) 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: --- .changeset/strong-lions-listen.md | 5 +++++ lib/utils/__tests__/report.test.js | 2 +- lib/utils/report.js | 15 ++++++++++++--- 3 files changed, 18 insertions(+), 4 deletions(-) create mode 100644 .changeset/strong-lions-listen.md diff --git a/.changeset/strong-lions-listen.md b/.changeset/strong-lions-listen.md new file mode 100644 index 0000000000..452fb0aed5 --- /dev/null +++ b/.changeset/strong-lions-listen.md @@ -0,0 +1,5 @@ +--- +"stylelint": patch +--- + +Fixed: `printf`-like formatting for custom messages diff --git a/lib/utils/__tests__/report.test.js b/lib/utils/__tests__/report.test.js index c9286ba6b0..7887bd394c 100644 --- a/lib/utils/__tests__/report.test.js +++ b/lib/utils/__tests__/report.test.js @@ -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, }, diff --git a/lib/utils/report.js b/lib/utils/report.js index 23773751d5..a84ae5e808 100644 --- a/lib/utils/report.js +++ b/lib/utils/report.js @@ -1,7 +1,5 @@ 'use strict'; -const util = require('util'); - /** * Report a problem. * @@ -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} args + * @returns {string} + */ +function printfLike(format, ...args) { + return args.reduce((/** @type {string} */ result, arg) => { + return result.replace(/%[ds]/, String(arg)); + }, format); +}