Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 64 additions & 4 deletions shell/plugins/menu/MenuModel.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,67 @@
function stripJsonc(raw) {
return String(raw || "")
.replace(/^\s*\/\/[^\n]*(\n|$)/gm, "")
.replace(/,(\s*[}\]])/g, "$1")
var str = String(raw || "")
var out = ""
var inString = false
var quoteChar = ""
var escaped = false
var inLineComment = false
var inBlockComment = false

for (var i = 0; i < str.length; i++) {
var ch = str.charAt(i)
var next = str.charAt(i + 1)

if (inLineComment) {
if (ch === "\n") {
inLineComment = false
out += ch
}
continue
}

if (inBlockComment) {
if (ch === "*" && next === "/") {
inBlockComment = false
i++
}
continue
}

if (inString) {
out += ch
if (escaped) {
escaped = false
} else if (ch === "\\") {
escaped = true
} else if (ch === quoteChar) {
inString = false
}
continue
}

if (ch === '"' || ch === "'") {
inString = true
quoteChar = ch
out += ch
continue
}

if (ch === "/" && next === "/") {
inLineComment = true
i++
continue
}

if (ch === "/" && next === "*") {
inBlockComment = true
i++
continue
}

out += ch
}

return out.replace(/,(\s*[}\]])/g, "$1")
}

function normalizeAliases(value) {
Expand Down Expand Up @@ -49,7 +109,7 @@ function parseMenuJsonc(raw) {
} catch (e) {
return []
}
if (typeof parsed !== "object" || parsed === null) return []
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return []

var source = (parsed.items && typeof parsed.items === "object" && !Array.isArray(parsed.items))
? parsed.items
Expand Down
2 changes: 2 additions & 0 deletions test/shell.d/menu-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ const parsed = menu.parseMenuJsonc(`
`)

assertEqual(parsed.length, 3, 'menu parses JSONC with comments and trailing commas')
assertEqual(menu.parseMenuJsonc('[{"label": "item"}]').length, 0, 'menu rejects root arrays')
assertEqual(menu.parseMenuJsonc('{\n "items": {\n "item": { "label": "https://example.com" /* block */ } // inline\n }\n}')[0].label, 'https://example.com', 'menu handles inline comments and slashes in strings')
assertDeepEqual(
parsed.find(item => item.id === 'style.theme'),
{
Expand Down