Simplify directory scanning

This commit is contained in:
Alex Yatskov 2016-06-11 13:13:16 -07:00
parent 87e5073c63
commit 53ecefabcd
3 changed files with 22 additions and 50 deletions

31
core.go
View File

@ -53,37 +53,16 @@ func (gs *goldsmith) pushContext(plug Plugin) *context {
} }
func (gs *goldsmith) cleanupFiles() { func (gs *goldsmith) cleanupFiles() {
files := make(chan string) infos := make(chan fileInfo)
dirs := make(chan string) go scanDir(gs.dstDir, infos)
go scanDir(gs.dstDir, files, dirs)
for files != nil || dirs != nil { for info := range infos {
var ( relPath, _ := filepath.Rel(gs.dstDir, info.path)
path string
ok bool
)
select {
case path, ok = <-files:
if !ok {
files = nil
continue
}
case path, ok = <-dirs:
if !ok {
dirs = nil
continue
}
default:
continue
}
relPath, _ := filepath.Rel(gs.dstDir, path)
if contained, _ := gs.refs[relPath]; contained { if contained, _ := gs.refs[relPath]; contained {
continue continue
} }
os.RemoveAll(path) os.RemoveAll(info.path)
} }
} }

View File

@ -27,12 +27,16 @@ import "path/filepath"
type loader struct{} type loader struct{}
func (*loader) Initialize(ctx Context) error { func (*loader) Initialize(ctx Context) error {
files := make(chan string) infos := make(chan fileInfo)
go scanDir(ctx.SrcDir(), files, nil) go scanDir(ctx.SrcDir(), infos)
for path := range files { for info := range infos {
relPath, _ := filepath.Rel(ctx.SrcDir(), path) if info.IsDir() {
f := NewFileFromAsset(relPath, path) continue
}
relPath, _ := filepath.Rel(ctx.SrcDir(), info.path)
f := NewFileFromAsset(relPath, info.path)
ctx.DispatchFile(f) ctx.DispatchFile(f)
} }

27
util.go
View File

@ -27,6 +27,11 @@ import (
"path/filepath" "path/filepath"
) )
type fileInfo struct {
os.FileInfo
path string
}
func cleanPath(path string) string { func cleanPath(path string) string {
if filepath.IsAbs(path) { if filepath.IsAbs(path) {
var err error var err error
@ -38,31 +43,15 @@ func cleanPath(path string) string {
return filepath.Clean(path) return filepath.Clean(path)
} }
func scanDir(root string, files, dirs chan string) { func scanDir(root string, infos chan fileInfo) {
defer func() { defer close(infos)
if files != nil {
close(files)
}
if dirs != nil {
close(dirs)
}
}()
filepath.Walk(root, func(path string, info os.FileInfo, err error) error { filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil { if err != nil {
return err return err
} }
if info.IsDir() { infos <- fileInfo{FileInfo: info, path: path}
if dirs != nil {
dirs <- path
}
} else {
if files != nil {
files <- path
}
}
return nil return nil
}) })
} }