add Export feature for package gres

This commit is contained in:
John Guo
2021-12-14 23:01:20 +08:00
parent 4c7e409e61
commit bc2ce19876
3 changed files with 53 additions and 3 deletions

View File

@ -77,6 +77,11 @@ func ScanDirFile(path string, pattern string, recursive ...bool) []*File {
return defaultResource.ScanDirFile(path, pattern, recursive...)
}
// Export exports and saves specified path `src` and all its sub files to specified system path `dst` recursively.
func Export(src, dst string) error {
return defaultResource.Export(src, dst)
}
// Dump prints the files of the default resource object.
func Dump() {
defaultResource.Dump()

View File

@ -224,12 +224,38 @@ func (r *Resource) doScanDir(path string, pattern string, recursive bool, onlyFi
return files
}
// Export exports and saves specified path `src` and all its sub files to specified system path `dst` recursively.
func (r *Resource) Export(src, dst string) error {
var (
err error
path string
files = r.doScanDir(src, "*", true, false)
)
for _, file := range files {
path = gfile.Join(dst, file.Name())
if file.FileInfo().IsDir() {
err = gfile.Mkdir(path)
} else {
err = gfile.PutBytes(path, file.Content())
}
if err != nil {
return err
}
}
return nil
}
// Dump prints the files of current resource object.
func (r *Resource) Dump() {
var info os.FileInfo
r.tree.Iterator(func(key, value interface{}) bool {
info = value.(*File).FileInfo()
fmt.Printf("%v %7s %s\n", gtime.New(info.ModTime()).ISO8601(), gfile.FormatSize(info.Size()), key)
fmt.Printf(
"%v %7s %s\n",
gtime.New(info.ModTime()).ISO8601(),
gfile.FormatSize(info.Size()),
key,
)
return true
})
fmt.Printf("TOTAL FILES: %d\n", r.tree.Size())

View File

@ -7,11 +7,11 @@
package gres_test
import (
_ "github.com/gogf/gf/v2/os/gres/testdata/data"
"strings"
"testing"
_ "github.com/gogf/gf/v2/os/gres/testdata/data"
"github.com/gogf/gf/v2/debug/gdebug"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gfile"
@ -231,3 +231,22 @@ func Test_ScanDirFile(t *testing.T) {
t.Assert(files[0].Content(), "sub-test2 content")
})
}
func Test_Export(t *testing.T) {
gres.Dump()
gtest.C(t, func(t *gtest.T) {
var (
src = `template`
dst = gfile.TempDir(gtime.TimestampNanoStr())
err = gres.Export(src, dst)
)
defer gfile.Remove(dst)
t.AssertNil(err)
files, err := gfile.ScanDir(dst, "*", true)
t.AssertNil(err)
t.Assert(len(files), 14)
name := `template/index.html`
t.Assert(gfile.GetContents(gfile.Join(dst, name)), gres.GetContent(name))
})
}