24 lines
1.0 KiB
TypeScript
24 lines
1.0 KiB
TypeScript
export function iniValue(content: string, key: string): string {
|
|
const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
const match = content.match(new RegExp(`^[ \\t]*${escapedKey}[ \\t]*=[ \\t]*(.*?)[ \\t]*$`, "mi"));
|
|
return match?.[1] ?? "";
|
|
}
|
|
|
|
export function updateIniValues(content: string, changes: Record<string, string>): string {
|
|
const newline = content.includes("\r\n") ? "\r\n" : "\n";
|
|
const lines = content.replace(/\r\n/g, "\n").split("\n");
|
|
const changed = new Set<string>();
|
|
const output = lines.map((line) => {
|
|
const match = line.match(/^\s*([^=\s]+)\s*=.*$/);
|
|
if (!match || changes[match[1]] === undefined) return line;
|
|
changed.add(match[1]);
|
|
return `${match[1]}=${changes[match[1]]}`;
|
|
});
|
|
const missing = Object.entries(changes).filter(([key]) => !changed.has(key));
|
|
if (missing.length) {
|
|
if (output.length && output[output.length - 1] !== "") output.push("");
|
|
output.push(...missing.map(([key, value]) => `${key}=${value}`));
|
|
}
|
|
return output.join(newline);
|
|
}
|