@@ -4,6 +4,7 @@ import { access, readFile, unlink, writeFile } from 'fs/promises';
44import { basename , dirname , join } from 'path' ;
55
66import { applyPatch , parsePatch , reversePatch } from 'diff' ;
7+ import { patch } from 'semver' ;
78
89export interface ShouldApplyWithReason {
910 shouldApply : boolean ;
@@ -18,7 +19,7 @@ export abstract class FileModification {
1819 public constructor ( protected readonly logger : Logger ) { }
1920
2021 // This is the main method that child classes need to implement
21- protected abstract generatePatch ( ) : Promise < string > ;
22+ protected abstract generatePatch ( overridePath ?: string ) : Promise < string > ;
2223
2324 private getPatchFilePath ( targetFile : string ) : string {
2425 const dir = dirname ( targetFile ) ;
@@ -64,8 +65,14 @@ export abstract class FileModification {
6465 }
6566
6667 private async applyPatch ( patchContents : string ) : Promise < void > {
68+ if ( ! patchContents . trim ( ) ) {
69+ throw new Error ( 'Patch contents are empty' ) ;
70+ }
6771 const currentContent = await readFile ( this . filePath , 'utf8' ) ;
6872 const parsedPatch = parsePatch ( patchContents ) [ 0 ] ;
73+ if ( ! parsedPatch ?. hunks . length ) {
74+ throw new Error ( 'Invalid Patch Format: No hunks found' ) ;
75+ }
6976 const results = applyPatch ( currentContent , parsedPatch ) ;
7077 if ( results === false ) {
7178 throw new Error ( `Failed to apply patch to ${ this . filePath } ` ) ;
@@ -75,22 +82,26 @@ export abstract class FileModification {
7582
7683 // Default implementation of apply that uses the patch
7784 async apply ( ) : Promise < void > {
78- // First attempt to apply the patch that was generated
79- const staticPatch = await this . getPregeneratedPatch ( ) ;
80- if ( staticPatch ) {
81- try {
82- await this . applyPatch ( staticPatch ) ;
83- await this . savePatch ( staticPatch ) ;
84- return ;
85- } catch ( error ) {
86- this . logger . error (
87- `Failed to apply static patch to ${ this . filePath } , continuing with dynamic patch`
88- ) ;
85+ try {
86+ // First attempt to apply the patch that was generated
87+ const staticPatch = await this . getPregeneratedPatch ( ) ;
88+ if ( staticPatch ) {
89+ try {
90+ await this . applyPatch ( staticPatch ) ;
91+ await this . savePatch ( staticPatch ) ;
92+ return ;
93+ } catch ( error ) {
94+ this . logger . error (
95+ `Failed to apply static patch to ${ this . filePath } , continuing with dynamic patch`
96+ ) ;
97+ }
8998 }
99+ const patchContents = await this . generatePatch ( ) ;
100+ await this . applyPatch ( patchContents ) ;
101+ await this . savePatch ( patchContents ) ;
102+ } catch ( err ) {
103+ this . logger . error ( `Failed to apply patch to ${ this . filePath } : ${ err } ` ) ;
90104 }
91- const patchContents = await this . generatePatch ( ) ;
92- await this . applyPatch ( patchContents ) ;
93- await this . savePatch ( patchContents ) ;
94105 }
95106
96107 // Update rollback to use the shared utility
0 commit comments