From c6e056f791cda2d63adbe5a94be0b4cf3bb1f8a3 Mon Sep 17 00:00:00 2001 From: FuXiaoHei Date: Sun, 8 May 2022 11:31:41 +0800 Subject: [PATCH] feat: support watching subdirectories --- pkg/core/generator/generate.go | 11 +++++++++++ pkg/utils/file.go | 13 +++++++++++++ pkg/utils/slice.go | 14 ++++++++++++++ 3 files changed, 38 insertions(+) diff --git a/pkg/core/generator/generate.go b/pkg/core/generator/generate.go index ec1229e..b1532db 100644 --- a/pkg/core/generator/generate.go +++ b/pkg/core/generator/generate.go @@ -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) } diff --git a/pkg/utils/file.go b/pkg/utils/file.go index 3e36120..c12d8df 100644 --- a/pkg/utils/file.go +++ b/pkg/utils/file.go @@ -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 +} diff --git a/pkg/utils/slice.go b/pkg/utils/slice.go index bd5bc55..68ad295 100644 --- a/pkg/utils/slice.go +++ b/pkg/utils/slice.go @@ -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 +}