(doc: TextDocument)
| 105 | } |
| 106 | |
| 107 | async function editBindingsDoc(doc: TextDocument) { |
| 108 | const text = doc.getText(); |
| 109 | // return undefined if text is an empty string |
| 110 | const node = parseTree(text) as Node | undefined; |
| 111 | |
| 112 | let updatedText; |
| 113 | if (node && node.type !== "array") { |
| 114 | // Replace directly if it is not array, that means the keybindings contains the wrong config. |
| 115 | updatedText = JSON.stringify(requiredBindings, undefined, "\t"); |
| 116 | } else { |
| 117 | // Else = if the either the node is not undefined, could be all comments |
| 118 | // or it is an array type and has children |
| 119 | updatedText = text; |
| 120 | |
| 121 | // Setup lookup tables |
| 122 | const requiredMap = new Map<string, KeyBinding>(); |
| 123 | for (const b of requiredBindings) { |
| 124 | requiredMap.set(toHashKey(b), b); |
| 125 | } |
| 126 | const legacySet = new Set<string>(); |
| 127 | for (const b of legacyBindings) { |
| 128 | legacySet.add(toHashKey(b)); |
| 129 | } |
| 130 | const modOptions = { formattingOptions: { insertSpaces: false } }; |
| 131 | |
| 132 | // If the root node is an array and has children |
| 133 | if (node && node.type === "array" && node.children) { |
| 134 | for (let i = 0; i < node.children?.length ?? 0; i++) { |
| 135 | const idx = node.children.length - i - 1; |
| 136 | const child = node.children[idx]; |
| 137 | const v = getNodeValue(child) as KeyBinding; |
| 138 | const key = toHashKey(v); |
| 139 | |
| 140 | if (legacySet.has(key)) { |
| 141 | // Remove the legacy config |
| 142 | const path = [idx] as JSONPath; |
| 143 | const edits = modify( |
| 144 | updatedText, |
| 145 | path, |
| 146 | undefined, |
| 147 | modOptions |
| 148 | ); |
| 149 | updatedText = applyEdits(updatedText, edits); |
| 150 | node.children.splice(idx, 1); |
| 151 | } else if (requiredMap.has(key)) { |
| 152 | // Exclude the bindings that exist |
| 153 | requiredMap.delete(key); |
| 154 | } |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | // Append (using update) to the text to avoid removal of comments the much as possible |
| 159 | let index = node?.children?.length ?? 0; |
| 160 | for (const binding of requiredMap.values()) { |
| 161 | const path = [index] as JSONPath; |
| 162 | const edits = modify(updatedText, path, binding, modOptions); |
| 163 | updatedText = applyEdits(updatedText, edits); |
| 164 | index++; |
no test coverage detected