Skip to content

Commit d0f12b1

Browse files
committed
review: update string replace
1 parent d54fa52 commit d0f12b1

1 file changed

Lines changed: 12 additions & 2 deletions

File tree

pkg/util/fileops.go

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package util
22

33
import (
4+
"fmt"
45
"io"
56
"os"
67
"path/filepath"
@@ -73,13 +74,22 @@ func CopyDir(src, dst string) error {
7374
return nil
7475
}
7576

76-
// ModifyFile replaces all occurrences of oldStr with newStr in the file
77+
// ModifyFile replaces all occurrences of oldStr with newStr in the file.
78+
// Returns an error if no replacements were made
7779
func ModifyFile(path, oldStr, newStr string) error {
7880
content, err := os.ReadFile(path)
7981
if err != nil {
8082
return err
8183
}
82-
modified := strings.ReplaceAll(string(content), oldStr, newStr)
84+
85+
original := string(content)
86+
modified := strings.ReplaceAll(original, oldStr, newStr)
87+
88+
// Error if no replacements were made
89+
if modified == original {
90+
return fmt.Errorf("pattern %q not found in file %s", oldStr, path)
91+
}
92+
8393
return os.WriteFile(path, []byte(modified), 0644)
8494
}
8595

0 commit comments

Comments
 (0)