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() {
files := make(chan string)
dirs := make(chan string)
go scanDir(gs.dstDir, files, dirs)
infos := make(chan fileInfo)
go scanDir(gs.dstDir, infos)
for files != nil || dirs != nil {
var (
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)
for info := range infos {
relPath, _ := filepath.Rel(gs.dstDir, info.path)
if contained, _ := gs.refs[relPath]; contained {
continue
}
os.RemoveAll(path)
os.RemoveAll(info.path)
}
}

View File

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

27
util.go
View File

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