Skip to content

Commit a009a8c

Browse files
authored
ci: improve theme preview action (anuraghazra#2572)
1 parent b17444e commit a009a8c

File tree

1 file changed

+30
-11
lines changed

1 file changed

+30
-11
lines changed

scripts/preview-theme.js

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -312,18 +312,30 @@ const parseJSON = (json) => {
312312
);
313313
}
314314
} catch (error) {
315-
let parsedJson = json
315+
// Remove trailing commas (if any).
316+
let parsedJson = json.replace(/(,\s*})/g, "}");
317+
318+
// Remove JS comments (if any).
319+
parsedJson = parsedJson.replace(/\/\/[A-z\s]*\s/g, "");
320+
321+
// Fix incorrect open bracket (if any).
322+
const splitJson = parsedJson
316323
.split(/([\s\r\s]*}[\s\r\s]*,[\s\r\s]*)(?=[\w"-]+:)/)
317-
.filter((x) => typeof x !== "string" || !!x.trim());
318-
if (parsedJson[0].replace(/\s+/g, "") === "},") {
319-
parsedJson[0] = "},";
320-
if (!/\s*}\s*,?\s*$/.test(parsedJson[1])) {
321-
parsedJson.push(parsedJson.shift());
324+
.filter((x) => typeof x !== "string" || !!x.trim()); // Split json into array of strings and objects.
325+
if (splitJson[0].replace(/\s+/g, "") === "},") {
326+
splitJson[0] = "},";
327+
if (!/\s*}\s*,?\s*$/.test(splitJson[1])) {
328+
splitJson.push(splitJson.shift());
322329
} else {
323-
parsedJson.shift();
330+
splitJson.shift();
324331
}
325-
return Hjson.parse(parsedJson.join(""));
326-
} else {
332+
parsedJson = splitJson.join("");
333+
}
334+
335+
// Try to parse the fixed json.
336+
try {
337+
return Hjson.parse(parsedJson);
338+
} catch (error) {
327339
throw new IncorrectJsonFormatError(
328340
`Theme JSON file could not be parsed: ${error.message}`,
329341
);
@@ -387,10 +399,17 @@ export const run = async () => {
387399
// Retrieve theme changes from the PR diff.
388400
debug("Retrieve themes...");
389401
const diff = parse(res.data);
402+
403+
// Retrieve all theme changes from the PR diff and convert to JSON.
404+
debug("Retrieve theme changes...");
390405
const content = diff
391406
.find((file) => file.to === "themes/index.js")
392-
.chunks[0].changes.filter((c) => c.type === "add")
393-
.map((c) => c.content.replace("+", ""))
407+
.chunks.map((chunk) =>
408+
chunk.changes
409+
.filter((c) => c.type === "add")
410+
.map((c) => c.content.replace("+", ""))
411+
.join(""),
412+
)
394413
.join("");
395414
const themeObject = parseJSON(content);
396415
if (

0 commit comments

Comments
 (0)