gfile_replace.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2017-2018 gf Author(https://github.com/gogf/gf). 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. package gfile
  7. import (
  8. "github.com/gogf/gf/text/gstr"
  9. )
  10. // ReplaceFile replaces content for file <path>.
  11. func ReplaceFile(search, replace, path string) error {
  12. return PutContents(path, gstr.Replace(GetContents(path), search, replace))
  13. }
  14. // ReplaceFileFunc replaces content for file <path> with callback function <f>.
  15. func ReplaceFileFunc(f func(path, content string) string, path string) error {
  16. data := GetContents(path)
  17. result := f(path, data)
  18. if len(data) != len(result) && data != result {
  19. return PutContents(path, result)
  20. }
  21. return nil
  22. }
  23. // ReplaceDir replaces content for files under <path>.
  24. // The parameter <pattern> specifies the file pattern which matches to be replaced.
  25. // It does replacement recursively if given parameter <recursive> is true.
  26. func ReplaceDir(search, replace, path, pattern string, recursive ...bool) error {
  27. files, err := ScanDirFile(path, pattern, recursive...)
  28. if err != nil {
  29. return err
  30. }
  31. for _, file := range files {
  32. if err = ReplaceFile(search, replace, file); err != nil {
  33. return err
  34. }
  35. }
  36. return err
  37. }
  38. // ReplaceDirFunc replaces content for files under <path> with callback function <f>.
  39. // The parameter <pattern> specifies the file pattern which matches to be replaced.
  40. // It does replacement recursively if given parameter <recursive> is true.
  41. func ReplaceDirFunc(f func(path, content string) string, path, pattern string, recursive ...bool) error {
  42. files, err := ScanDirFile(path, pattern, recursive...)
  43. if err != nil {
  44. return err
  45. }
  46. for _, file := range files {
  47. if err = ReplaceFileFunc(f, file); err != nil {
  48. return err
  49. }
  50. }
  51. return err
  52. }