Files
cell/scripts/toml.js
John Alanbrook 939269b060
Some checks failed
Build and Deploy / build-macos (push) Failing after 7s
Build and Deploy / build-linux (push) Has been cancelled
Build and Deploy / build-windows (CLANG64) (push) Has been cancelled
Build and Deploy / package-dist (push) Has been cancelled
Build and Deploy / deploy-itch (push) Has been cancelled
Build and Deploy / deploy-gitea (push) Has been cancelled
initial modules attempt
2025-05-29 18:48:19 -05:00

105 lines
2.5 KiB
JavaScript

// Simple TOML parser for shop.toml
// Supports basic TOML features needed for the module system
function parse_toml(text) {
var lines = text.split('\n')
var result = {}
var current_section = result
var current_section_name = ''
for (var i = 0; i < lines.length; i++) {
var line = lines[i].trim()
// Skip empty lines and comments
if (!line || line.startsWith('#')) continue
// Section header
if (line.startsWith('[') && line.endsWith(']')) {
var section_path = line.slice(1, -1).split('.')
current_section = result
current_section_name = section_path.join('.')
for (var j = 0; j < section_path.length; j++) {
var key = section_path[j]
if (!current_section[key]) {
current_section[key] = {}
}
current_section = current_section[key]
}
continue
}
// Key-value pair
var eq_index = line.indexOf('=')
if (eq_index > 0) {
var key = line.substring(0, eq_index).trim()
var value = line.substring(eq_index + 1).trim()
// Parse value
if (value.startsWith('"') && value.endsWith('"')) {
// String
current_section[key] = value.slice(1, -1)
} else if (value.startsWith('[') && value.endsWith(']')) {
// Array
current_section[key] = parse_array(value)
} else if (value === 'true' || value === 'false') {
// Boolean
current_section[key] = value === 'true'
} else if (!isNaN(Number(value))) {
// Number
current_section[key] = Number(value)
} else {
// Unquoted string
current_section[key] = value
}
}
}
return result
}
function parse_array(str) {
// Remove brackets
str = str.slice(1, -1).trim()
if (!str) return []
var items = []
var current = ''
var in_quotes = false
for (var i = 0; i < str.length; i++) {
var char = str[i]
if (char === '"' && (i === 0 || str[i-1] !== '\\')) {
in_quotes = !in_quotes
current += char
} else if (char === ',' && !in_quotes) {
items.push(parse_value(current.trim()))
current = ''
} else {
current += char
}
}
if (current.trim()) {
items.push(parse_value(current.trim()))
}
return items
}
function parse_value(str) {
if (str.startsWith('"') && str.endsWith('"')) {
return str.slice(1, -1)
} else if (str === 'true' || str === 'false') {
return str === 'true'
} else if (!isNaN(Number(str))) {
return Number(str)
} else {
return str
}
}
return {
parse: parse_toml
}