|
| 1 | +import * as fs from "fs"; |
| 2 | +import commentJson from "comment-json"; |
| 3 | + |
| 4 | +// A helper function to recursively sort object keys alphabetically. |
| 5 | +function sortObjectKeys<T>(obj: T): T { |
| 6 | + if (obj && typeof obj === "object" && !Array.isArray(obj)) { |
| 7 | + const sorted = {} as any; |
| 8 | + Object.keys(obj) |
| 9 | + .sort() |
| 10 | + .forEach((key) => { |
| 11 | + // Recursively sort keys if the value is an object |
| 12 | + sorted[key] = sortObjectKeys((obj as any)[key]); |
| 13 | + }); |
| 14 | + return sorted; |
| 15 | + } |
| 16 | + return obj; |
| 17 | +} |
| 18 | + |
| 19 | +export function sortFiles() { |
| 20 | + const filePath = new URL( |
| 21 | + "../../inputfiles/overridingTypes.jsonc", |
| 22 | + import.meta.url, |
| 23 | + ); // Replace with your JSONC file path |
| 24 | + |
| 25 | + // Read the JSONC file content |
| 26 | + const fileContent = fs.readFileSync(filePath, "utf-8"); |
| 27 | + |
| 28 | + // Parse the JSONC file while preserving comments |
| 29 | + const parsed = commentJson.parse(fileContent, undefined, true); |
| 30 | + |
| 31 | + // Sort the object keys alphabetically (recursively) |
| 32 | + const sortedObject = sortObjectKeys(parsed); |
| 33 | + |
| 34 | + // Stringify the sorted object back to JSONC format (preserving comments) |
| 35 | + const sortedJsonC = commentJson.stringify(sortedObject, null, 2); |
| 36 | + |
| 37 | + // Write the sorted content back to the file |
| 38 | + fs.writeFileSync(filePath, sortedJsonC, "utf-8"); |
| 39 | + |
| 40 | + console.log("JSONC file keys sorted successfully."); |
| 41 | +} |
0 commit comments