diff --git a/shell/plugins/menu/MenuModel.js b/shell/plugins/menu/MenuModel.js index c6c75f254fff..33e0711a0714 100644 --- a/shell/plugins/menu/MenuModel.js +++ b/shell/plugins/menu/MenuModel.js @@ -1,7 +1,26 @@ function stripJsonc(raw) { - return String(raw || "") - .replace(/^\s*\/\/[^\n]*(\n|$)/gm, "") - .replace(/,(\s*[}\]])/g, "$1") + var s = String(raw || "").replace(/^\s*\/\/[^\n]*(\n|$)/gm, ""); + var out = ""; + var inString = false; + var escape = false; + for (var i = 0; i < s.length; i++) { + var c = s[i]; + if (escape) { + escape = false; + } else if (c === '"') { + inString = !inString; + } else if (c === '\\' && inString) { + escape = true; + } + + if (!inString && c === ',') { + var j = i + 1; + while (j < s.length && /\s/.test(s[j])) j++; + if (j < s.length && (s[j] === '}' || s[j] === ']')) continue; + } + out += c; + } + return out; } function normalizeAliases(value) { diff --git a/test/shell.d/menu-test.sh b/test/shell.d/menu-test.sh index 3a73db494ca8..96de8ec10b62 100644 --- a/test/shell.d/menu-test.sh +++ b/test/shell.d/menu-test.sh @@ -40,6 +40,14 @@ const parsed = menu.parseMenuJsonc(` `) assertEqual(parsed.length, 3, 'menu parses JSONC with comments and trailing commas') + +// String-aware trailing commas (#13250) +const withCommasInStrings = menu.parseMenuJsonc('{\n "b": { "label": "x, ]y", "action": "mv f{.bak,}" },\n}') +assertEqual(withCommasInStrings[0].label, 'x, ]y', 'menu keeps a comma before ] inside a label') +assertEqual(withCommasInStrings[0].action, 'mv f{.bak,}', 'menu keeps a comma before } inside an action') +assertEqual(menu.parseMenuJsonc('{"a": {"label": "q\\\\"},}')[0].label, 'q\\', 'menu ends a string at a quote after an escaped backslash before a trailing comma') +assertEqual(menu.parseMenuJsonc('{"a": {"label": "say \\"hi, }"}}')[0].label, 'say "hi, }', 'menu keeps a comma before } after an escaped quote inside a label') + assertDeepEqual( parsed.find(item => item.id === 'style.theme'), {