( root: string, rel: string, find: string, replace: string, occurrence: 'first' | 'all' = 'first' )
| 1123 | } |
| 1124 | |
| 1125 | export async function replaceInNote( |
| 1126 | root: string, |
| 1127 | rel: string, |
| 1128 | find: string, |
| 1129 | replace: string, |
| 1130 | occurrence: 'first' | 'all' = 'first' |
| 1131 | ): Promise<{ meta: NoteMeta; replacements: number }> { |
| 1132 | if (!find) throw new Error('find is required') |
| 1133 | const abs = resolveSafe(root, rel) |
| 1134 | const body = await fs.readFile(abs, 'utf8') |
| 1135 | let replacements = 0 |
| 1136 | let next: string |
| 1137 | if (occurrence === 'all') { |
| 1138 | const parts = body.split(find) |
| 1139 | replacements = parts.length - 1 |
| 1140 | next = parts.join(replace) |
| 1141 | } else { |
| 1142 | const idx = body.indexOf(find) |
| 1143 | if (idx < 0) { |
| 1144 | next = body |
| 1145 | } else { |
| 1146 | next = body.slice(0, idx) + replace + body.slice(idx + find.length) |
| 1147 | replacements = 1 |
| 1148 | } |
| 1149 | } |
| 1150 | if (replacements === 0) { |
| 1151 | const folder = folderOf(root, abs) |
| 1152 | if (!folder) throw new Error(`Note not in a known folder: ${rel}`) |
| 1153 | return { meta: await readMeta(root, abs, folder), replacements: 0 } |
| 1154 | } |
| 1155 | await fs.writeFile(abs, next, 'utf8') |
| 1156 | const folder = folderOf(root, abs) |
| 1157 | if (!folder) throw new Error(`Note not in a known folder: ${rel}`) |
| 1158 | return { meta: await readMeta(root, abs, folder), replacements } |
| 1159 | } |
| 1160 | |
| 1161 | export async function insertAtLine( |
| 1162 | root: string, |
no test coverage detected