@@ -85,15 +85,55 @@ export class FsWrite {
8585 }
8686
8787 private static async handleStrReplace ( command : StrReplaceCommand , sanitizedPath : string ) : Promise < void > {
88- // TODO
88+ const fileContent = await fs . readFileText ( sanitizedPath )
89+
90+ const matches = [ ...fileContent . matchAll ( new RegExp ( this . escapeRegExp ( command . oldStr ) , 'g' ) ) ]
91+
92+ if ( matches . length === 0 ) {
93+ throw new Error ( `No occurrences of "${ command . oldStr } " were found` )
94+ }
95+ if ( matches . length > 1 ) {
96+ throw new Error ( `${ matches . length } occurrences of oldStr were found when only 1 is expected` )
97+ }
98+
99+ const newContent = fileContent . replace ( command . oldStr , command . newStr )
100+ await fs . writeFile ( sanitizedPath , newContent )
101+
102+ void vscode . window . showInformationMessage ( `Updated: ${ sanitizedPath } ` )
89103 }
90104
91105 private static async handleInsert ( command : InsertCommand , sanitizedPath : string ) : Promise < void > {
92- // TODO
106+ const fileContent = await fs . readFileText ( sanitizedPath )
107+ const lines = fileContent . split ( '\n' )
108+
109+ const numLines = lines . length
110+ const insertLine = Math . max ( 0 , Math . min ( command . insertLine , numLines ) )
111+
112+ let newContent : string
113+ if ( insertLine === 0 ) {
114+ newContent = command . newStr + '\n' + fileContent
115+ } else {
116+ newContent = [ ...lines . slice ( 0 , insertLine ) , command . newStr , ...lines . slice ( insertLine ) ] . join ( '\n' )
117+ }
118+
119+ await fs . writeFile ( sanitizedPath , newContent )
120+
121+ void vscode . window . showInformationMessage ( `Updated: ${ sanitizedPath } ` )
93122 }
94123
95124 private static async handleAppend ( command : AppendCommand , sanitizedPath : string ) : Promise < void > {
96- // TODO
125+ const fileContent = await fs . readFileText ( sanitizedPath )
126+ const needsNewline = fileContent . length !== 0 && ! fileContent . endsWith ( '\n' )
127+
128+ let contentToAppend = command . newStr
129+ if ( needsNewline ) {
130+ contentToAppend = '\n' + contentToAppend
131+ }
132+
133+ const newContent = fileContent + contentToAppend
134+ await fs . writeFile ( sanitizedPath , newContent )
135+
136+ void vscode . window . showInformationMessage ( `Updated: ${ sanitizedPath } ` )
97137 }
98138
99139 private static getCreateCommandText ( command : CreateCommand ) : string {
@@ -107,4 +147,8 @@ export class FsWrite {
107147 this . logger . warn ( 'No content provided for the create command' )
108148 return ''
109149 }
150+
151+ private static escapeRegExp ( string : string ) : string {
152+ return string . replace ( / [ . * + ? ^ $ { } ( ) | [ \] \\ ] / g, '\\$&' )
153+ }
110154}
0 commit comments