Skip to content

Commit

Permalink
feat: support watching subdirectories
Browse files Browse the repository at this point in the history
  • Loading branch information
fuxiaohei committed May 8, 2022
1 parent ab4d141 commit c6e056f
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
11 changes: 11 additions & 0 deletions pkg/core/generator/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,22 @@ func Watch(opt *Option) {
}
})

var allDirs []string
baseDir := filepath.Base(opt.OutputDir)
for _, dir := range constants.InitDirectories() {
if dir == baseDir {
continue
}
subDirs, err := utils.GetSubDirectories(dir)
if err != nil {
zlog.Warnf("get sub directories failed: %v", err)
allDirs = append(allDirs, dir)
} else {
allDirs = append(allDirs, subDirs...)
}
}
allDirs = utils.UniqueStringsSlice(allDirs)
for _, dir := range allDirs {
w.Add(dir)
zlog.Debugf("watching dir: %s", dir)
}
Expand Down
13 changes: 13 additions & 0 deletions pkg/utils/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,16 @@ func IsTempFile(fpath string) bool {
strings.HasPrefix(baseName, "#") // emacs
return istemp
}

// GetSubDirectories returns all subdirectories of a directory
// returning slice contains dir self
func GetSubDirectories(dir string) ([]string, error) {
var dirs []string
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if info != nil && info.IsDir() {
dirs = append(dirs, path)
}
return nil
})
return dirs, err
}
14 changes: 14 additions & 0 deletions pkg/utils/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,17 @@ func Contains[T comparable](s []T, target T) bool {
}
return false
}

// UniqueStringsSlice returns a unique slice of strings.
func UniqueStringsSlice(strSlice []string) []string {
keys := make(map[string]struct{})
list := []string{}

for _, entry := range strSlice {
if _, ok := keys[entry]; !ok {
keys[entry] = struct{}{}
list = append(list, entry)
}
}
return list
}

0 comments on commit c6e056f

Please sign in to comment.