( path: string, source: SourceConfig, )
| 40 | * Preserves existing comments and formatting. |
| 41 | */ |
| 42 | export const addSourceToConfig = ( |
| 43 | path: string, |
| 44 | source: SourceConfig, |
| 45 | ): Effect.Effect<void, PlatformError, FileSystem.FileSystem> => |
| 46 | Effect.gen(function* () { |
| 47 | const fs = yield* FileSystem.FileSystem; |
| 48 | let text = yield* readOrCreate(fs, path); |
| 49 | |
| 50 | // Ensure "sources" array exists |
| 51 | let tree = jsonc.parseTree(text); |
| 52 | let sourcesNode = tree ? jsonc.findNodeAtLocation(tree, ["sources"]) : undefined; |
| 53 | |
| 54 | if (!sourcesNode) { |
| 55 | const edits = jsonc.modify(text, ["sources"], [source], { |
| 56 | formattingOptions: FORMATTING, |
| 57 | }); |
| 58 | text = jsonc.applyEdits(text, edits); |
| 59 | } else { |
| 60 | // Remove existing entry with same namespace (if any) to avoid duplicates |
| 61 | const ns = "namespace" in source ? source.namespace : undefined; |
| 62 | if (ns && sourcesNode.children) { |
| 63 | for (let i = sourcesNode.children.length - 1; i >= 0; i--) { |
| 64 | const child = sourcesNode.children[i]!; |
| 65 | const nsNode = jsonc.findNodeAtLocation(child, ["namespace"]); |
| 66 | if (nsNode && jsonc.getNodeValue(nsNode) === ns) { |
| 67 | const edits = jsonc.modify(text, ["sources", i], undefined, { |
| 68 | formattingOptions: FORMATTING, |
| 69 | }); |
| 70 | text = jsonc.applyEdits(text, edits); |
| 71 | } |
| 72 | } |
| 73 | // Re-parse after removals |
| 74 | tree = jsonc.parseTree(text); |
| 75 | sourcesNode = tree ? jsonc.findNodeAtLocation(tree, ["sources"]) : undefined; |
| 76 | } |
| 77 | |
| 78 | const count = sourcesNode?.children?.length ?? 0; |
| 79 | const edits = jsonc.modify(text, ["sources", count], source, { |
| 80 | formattingOptions: FORMATTING, |
| 81 | }); |
| 82 | text = jsonc.applyEdits(text, edits); |
| 83 | } |
| 84 | |
| 85 | yield* fs.writeFileString(path, text); |
| 86 | }); |
| 87 | |
| 88 | /** |
| 89 | * Remove a source from the config file by namespace. |
no test coverage detected