2019-07-25 21:01:04 +08:00
|
|
|
// Copyright 2017-2018 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
|
|
|
//
|
|
|
|
// This Source Code Form is subject to the terms of the MIT License.
|
|
|
|
// If a copy of the MIT was not distributed with this file,
|
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
|
|
|
|
|
|
|
package gfile
|
|
|
|
|
|
|
|
import (
|
2019-07-29 21:01:19 +08:00
|
|
|
"github.com/gogf/gf/text/gstr"
|
2019-07-25 21:01:04 +08:00
|
|
|
)
|
|
|
|
|
2019-12-25 20:56:39 +08:00
|
|
|
// ReplaceFile replaces content for file <path>.
|
|
|
|
func ReplaceFile(search, replace, path string) error {
|
|
|
|
return PutContents(path, gstr.Replace(GetContents(path), search, replace))
|
|
|
|
}
|
|
|
|
|
|
|
|
// ReplaceFileFunc replaces content for file <path> with callback function <f>.
|
|
|
|
func ReplaceFileFunc(f func(path, content string) string, path string) error {
|
|
|
|
data := GetContents(path)
|
|
|
|
result := f(path, data)
|
|
|
|
if len(data) != len(result) && data != result {
|
|
|
|
return PutContents(path, result)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// ReplaceDir replaces content for files under <path>.
|
2019-07-25 21:01:04 +08:00
|
|
|
// The parameter <pattern> specifies the file pattern which matches to be replaced.
|
|
|
|
// It does replacement recursively if given parameter <recursive> is true.
|
2019-12-25 20:56:39 +08:00
|
|
|
func ReplaceDir(search, replace, path, pattern string, recursive ...bool) error {
|
2019-09-02 19:05:32 +08:00
|
|
|
files, err := ScanDirFile(path, pattern, recursive...)
|
2019-07-25 21:01:04 +08:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
for _, file := range files {
|
2019-12-25 20:56:39 +08:00
|
|
|
if err = ReplaceFile(search, replace, file); err != nil {
|
2019-07-25 21:01:04 +08:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-12-25 20:56:39 +08:00
|
|
|
// ReplaceDirFunc replaces content for files under <path> with callback function <f>.
|
2019-07-25 21:01:04 +08:00
|
|
|
// The parameter <pattern> specifies the file pattern which matches to be replaced.
|
|
|
|
// It does replacement recursively if given parameter <recursive> is true.
|
2019-12-25 20:56:39 +08:00
|
|
|
func ReplaceDirFunc(f func(path, content string) string, path, pattern string, recursive ...bool) error {
|
2019-09-02 19:05:32 +08:00
|
|
|
files, err := ScanDirFile(path, pattern, recursive...)
|
2019-07-25 21:01:04 +08:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
for _, file := range files {
|
2019-12-25 20:56:39 +08:00
|
|
|
if err = ReplaceFileFunc(f, file); err != nil {
|
|
|
|
return err
|
2019-07-25 21:01:04 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|