| 106 | * Will replace text from the source code. |
| 107 | */ |
| 108 | export class ReplaceChange implements Change { |
| 109 | order: number; |
| 110 | description: string; |
| 111 | |
| 112 | constructor( |
| 113 | public path: string, |
| 114 | private pos: number, |
| 115 | public oldText: string, |
| 116 | public newText: string, |
| 117 | ) { |
| 118 | if (pos < 0) { |
| 119 | throw new Error('Negative positions are invalid'); |
| 120 | } |
| 121 | this.description = `Replaced ${oldText} into position ${pos} of ${path} with ${newText}`; |
| 122 | this.order = pos; |
| 123 | } |
| 124 | |
| 125 | apply(host: Host): Promise<void> { |
| 126 | return host.read(this.path).then((content) => { |
| 127 | const prefix = content.substring(0, this.pos); |
| 128 | const suffix = content.substring(this.pos + this.oldText.length); |
| 129 | const text = content.substring(this.pos, this.pos + this.oldText.length); |
| 130 | |
| 131 | if (text !== this.oldText) { |
| 132 | return Promise.reject(new Error(`Invalid replace: "${text}" != "${this.oldText}".`)); |
| 133 | } |
| 134 | |
| 135 | // TODO: throw error if oldText doesn't match removed string. |
| 136 | return host.write(this.path, `${prefix}${this.newText}${suffix}`); |
| 137 | }); |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | export function applyToUpdateRecorder(recorder: UpdateRecorder, changes: Change[]): void { |
| 142 | for (const change of changes) { |
nothing calls this directly
no outgoing calls
no test coverage detected