github.com/gogf/gf/v2@v2.7.4/os/gfile/gfile_replace.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package gfile 8 9 import ( 10 "github.com/gogf/gf/v2/text/gstr" 11 ) 12 13 // ReplaceFile replaces content for file `path`. 14 func ReplaceFile(search, replace, path string) error { 15 return PutContents(path, gstr.Replace(GetContents(path), search, replace)) 16 } 17 18 // ReplaceFileFunc replaces content for file `path` with callback function `f`. 19 func ReplaceFileFunc(f func(path, content string) string, path string) error { 20 data := GetContents(path) 21 result := f(path, data) 22 if len(data) != len(result) || data != result { 23 return PutContents(path, result) 24 } 25 return nil 26 } 27 28 // ReplaceDir replaces content for files under `path`. 29 // The parameter `pattern` specifies the file pattern which matches to be replaced. 30 // It does replacement recursively if given parameter `recursive` is true. 31 func ReplaceDir(search, replace, path, pattern string, recursive ...bool) error { 32 files, err := ScanDirFile(path, pattern, recursive...) 33 if err != nil { 34 return err 35 } 36 for _, file := range files { 37 if err = ReplaceFile(search, replace, file); err != nil { 38 return err 39 } 40 } 41 return err 42 } 43 44 // ReplaceDirFunc replaces content for files under `path` with callback function `f`. 45 // The parameter `pattern` specifies the file pattern which matches to be replaced. 46 // It does replacement recursively if given parameter `recursive` is true. 47 func ReplaceDirFunc(f func(path, content string) string, path, pattern string, recursive ...bool) error { 48 files, err := ScanDirFile(path, pattern, recursive...) 49 if err != nil { 50 return err 51 } 52 for _, file := range files { 53 if err = ReplaceFileFunc(f, file); err != nil { 54 return err 55 } 56 } 57 return err 58 }