Skip to content

Commit ca87fc8

Browse files
committed
Rewrite of FindFilesInFolder using go-paths-helper
1 parent a8adcff commit ca87fc8

File tree

7 files changed

+62
-70
lines changed

7 files changed

+62
-70
lines changed

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ go 1.16
44

55
require (
66
github.com/arduino/board-discovery v0.0.0-20180823133458-1ba29327fb0c
7-
github.com/arduino/go-paths-helper v1.6.1
7+
github.com/arduino/go-paths-helper v1.7.0
88
github.com/arduino/go-properties-orderedmap v1.6.0
99
github.com/arduino/go-timeutils v0.0.0-20171220113728-d1dd9e313b1b
1010
github.com/arduino/go-win32-utils v0.0.0-20180330194947-ed041402e83b

go.sum

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,8 @@ github.com/arduino/board-discovery v0.0.0-20180823133458-1ba29327fb0c h1:agh2JT9
4848
github.com/arduino/board-discovery v0.0.0-20180823133458-1ba29327fb0c/go.mod h1:HK7SpkEax/3P+0w78iRQx1sz1vCDYYw9RXwHjQTB5i8=
4949
github.com/arduino/go-paths-helper v1.0.1/go.mod h1:HpxtKph+g238EJHq4geEPv9p+gl3v5YYu35Yb+w31Ck=
5050
github.com/arduino/go-paths-helper v1.2.0/go.mod h1:HpxtKph+g238EJHq4geEPv9p+gl3v5YYu35Yb+w31Ck=
51-
github.com/arduino/go-paths-helper v1.6.1 h1:lha+/BuuBsx0qTZ3gy6IO1kU23lObWdQ/UItkzVWQ+0=
52-
github.com/arduino/go-paths-helper v1.6.1/go.mod h1:V82BWgAAp4IbmlybxQdk9Bpkz8M4Qyx+RAFKaG9NuvU=
51+
github.com/arduino/go-paths-helper v1.7.0 h1:S9l5BP2aogz1CgyqqnncXt0PLpK4yvwOW/wu/LaR3tc=
52+
github.com/arduino/go-paths-helper v1.7.0/go.mod h1:V82BWgAAp4IbmlybxQdk9Bpkz8M4Qyx+RAFKaG9NuvU=
5353
github.com/arduino/go-properties-orderedmap v1.6.0 h1:gp2JoWRETtqwsZ+UHu/PBuYWYH2x2+d+uipDxS4WmvM=
5454
github.com/arduino/go-properties-orderedmap v1.6.0/go.mod h1:DKjD2VXY/NZmlingh4lSFMEYCVubfeArCsGPGDwb2yk=
5555
github.com/arduino/go-timeutils v0.0.0-20171220113728-d1dd9e313b1b h1:9hDi4F2st6dbLC3y4i02zFT5quS4X6iioWifGlVwfy4=

legacy/builder/builder.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,10 @@ var MAIN_FILE_VALID_EXTENSIONS = map[string]bool{".ino": true, ".pde": true}
3434
var ADDITIONAL_FILE_VALID_EXTENSIONS = map[string]bool{".h": true, ".c": true, ".hpp": true, ".hh": true, ".cpp": true, ".S": true}
3535
var ADDITIONAL_FILE_VALID_EXTENSIONS_NO_HEADERS = map[string]bool{".c": true, ".cpp": true, ".S": true}
3636

37+
var MainFileValidExtensions = []string{".ino", ".pde"}
38+
var AdditionalFileValidExtensions = []string{".h", ".c", ".hpp", ".hh", ".cpp", ".S"}
39+
var AdditionalFileValidExtensionsNoHeaders = []string{".c", ".cpp", ".S"}
40+
3741
const DEFAULT_DEBUG_LEVEL = 5
3842
const DEFAULT_WARNINGS_LEVEL = "none"
3943
const DEFAULT_SOFTWARE = "ARDUINO"

legacy/builder/container_find_includes.go

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -406,16 +406,13 @@ func findIncludesUntilDone(ctx *types.Context, cache *includeCache, sourceFile t
406406
}
407407

408408
func queueSourceFilesFromFolder(ctx *types.Context, queue *types.UniqueSourceFileQueue, origin interface{}, folder *paths.Path, recurse bool) error {
409-
extensions := func(ext string) bool { return ADDITIONAL_FILE_VALID_EXTENSIONS_NO_HEADERS[ext] }
410-
411-
filePaths := []string{}
412-
err := utils.FindFilesInFolder(&filePaths, folder.String(), extensions, recurse)
409+
filePaths, err := utils.FindFilesInFolder(folder, recurse, AdditionalFileValidExtensionsNoHeaders)
413410
if err != nil {
414411
return errors.WithStack(err)
415412
}
416413

417414
for _, filePath := range filePaths {
418-
sourceFile, err := types.MakeSourceFile(ctx, origin, paths.New(filePath))
415+
sourceFile, err := types.MakeSourceFile(ctx, origin, filePath)
419416
if err != nil {
420417
return errors.WithStack(err)
421418
}

legacy/builder/create_cmake_rule.go

Lines changed: 16 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,6 @@ package builder
1717

1818
import (
1919
"fmt"
20-
"io/ioutil"
21-
"os"
2220
"path/filepath"
2321
"regexp"
2422
"strings"
@@ -32,8 +30,10 @@ import (
3230
)
3331

3432
var VALID_EXPORT_EXTENSIONS = map[string]bool{".h": true, ".c": true, ".hpp": true, ".hh": true, ".cpp": true, ".S": true, ".a": true, ".properties": true}
35-
var DOTHEXTENSION = map[string]bool{".h": true, ".hh": true, ".hpp": true}
36-
var DOTAEXTENSION = map[string]bool{".a": true}
33+
34+
var ValidExportExtensions = []string{".h", ".c", ".hpp", ".hh", ".cpp", ".S", ".a", ".properties"}
35+
var DotHExtension = []string{".h", ".hh", ".hpp"}
36+
var DotAExtension = []string{".a"}
3737

3838
type ExportProjectCMake struct {
3939
// Was there an error while compiling the sketch?
@@ -66,7 +66,6 @@ func (s *ExportProjectCMake) Run(ctx *types.Context) error {
6666

6767
dynamicLibsFromPkgConfig := map[string]bool{}
6868
extensions := func(ext string) bool { return VALID_EXPORT_EXTENSIONS[ext] }
69-
staticLibsExtensions := func(ext string) bool { return DOTAEXTENSION[ext] }
7069
for _, library := range ctx.ImportedLibraries {
7170
// Copy used libraries in the correct folder
7271
libDir := libBaseFolder.Join(library.Name)
@@ -91,12 +90,11 @@ func (s *ExportProjectCMake) Run(ctx *types.Context) error {
9190
}
9291

9392
// Remove stray folders contining incompatible or not needed libraries archives
94-
var files []string
95-
utils.FindFilesInFolder(&files, libDir.Join("src").String(), staticLibsExtensions, true)
93+
files, _ := utils.FindFilesInFolder(libDir.Join("src"), true, DotAExtension)
9694
for _, file := range files {
97-
staticLibDir := filepath.Dir(file)
98-
if !isStaticLib || !strings.Contains(staticLibDir, mcu) {
99-
os.RemoveAll(staticLibDir)
95+
staticLibDir := file.Parent()
96+
if !isStaticLib || !strings.Contains(staticLibDir.String(), mcu) {
97+
staticLibDir.RemoveAll()
10098
}
10199
}
102100
}
@@ -128,11 +126,10 @@ func (s *ExportProjectCMake) Run(ctx *types.Context) error {
128126
}
129127

130128
// remove "#line 1 ..." from exported c_make folder sketch
131-
var sketchFiles []string
132-
utils.FindFilesInFolder(&sketchFiles, cmakeFolder.Join("sketch").String(), extensions, false)
129+
sketchFiles, _ := utils.FindFilesInFolder(cmakeFolder.Join("sketch"), false, ValidExportExtensions)
133130

134131
for _, file := range sketchFiles {
135-
input, err := ioutil.ReadFile(file)
132+
input, err := file.ReadFile()
136133
if err != nil {
137134
fmt.Println(err)
138135
continue
@@ -146,7 +143,7 @@ func (s *ExportProjectCMake) Run(ctx *types.Context) error {
146143
}
147144
}
148145
output := strings.Join(lines, "\n")
149-
err = ioutil.WriteFile(file, []byte(output), 0644)
146+
err = file.WriteFile([]byte(output))
150147
if err != nil {
151148
fmt.Println(err)
152149
}
@@ -163,14 +160,11 @@ func (s *ExportProjectCMake) Run(ctx *types.Context) error {
163160
extractCompileFlags(ctx, "recipe.cpp.o.pattern", &defines, &dynamicLibsFromGccMinusL, &linkerflags, &linkDirectories)
164161

165162
// Extract folders with .h in them for adding in include list
166-
var headerFiles []string
167-
isHeader := func(ext string) bool { return DOTHEXTENSION[ext] }
168-
utils.FindFilesInFolder(&headerFiles, cmakeFolder.String(), isHeader, true)
169-
foldersContainingDotH := findUniqueFoldersRelative(headerFiles, cmakeFolder.String())
163+
headerFiles, _ := utils.FindFilesInFolder(cmakeFolder, true, DotHExtension)
164+
foldersContainingDotH := findUniqueFoldersRelative(headerFiles.AsStrings(), cmakeFolder.String())
170165

171166
// Extract folders with .a in them for adding in static libs paths list
172-
var staticLibs []string
173-
utils.FindFilesInFolder(&staticLibs, cmakeFolder.String(), staticLibsExtensions, true)
167+
staticLibs, _ := utils.FindFilesInFolder(cmakeFolder, true, DotAExtension)
174168

175169
// Generate the CMakeLists global file
176170

@@ -210,13 +204,13 @@ func (s *ExportProjectCMake) Run(ctx *types.Context) error {
210204
cmakelist += "link_directories (" + strings.Join(relLinkDirectories, " ") + " ${EXTRA_LIBS_DIRS})\n"
211205
for _, staticLib := range staticLibs {
212206
// Static libraries are fully configured
213-
lib := filepath.Base(staticLib)
207+
lib := staticLib.Base()
214208
lib = strings.TrimPrefix(lib, "lib")
215209
lib = strings.TrimSuffix(lib, ".a")
216210
if !utils.SliceContains(dynamicLibsFromGccMinusL, lib) {
217211
linkGroup += " " + lib
218212
cmakelist += "add_library (" + lib + " STATIC IMPORTED)\n"
219-
location := strings.TrimPrefix(staticLib, cmakeFolder.String())
213+
location := strings.TrimPrefix(staticLib.String(), cmakeFolder.String())
220214
cmakelist += "set_property(TARGET " + lib + " PROPERTY IMPORTED_LOCATION " + "${PROJECT_SOURCE_DIR}" + location + " )\n"
221215
}
222216
}

legacy/builder/test/builder_test.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222
"time"
2323

2424
"github.com/arduino/go-paths-helper"
25+
"github.com/sirupsen/logrus"
2526

2627
"github.com/arduino/arduino-cli/legacy/builder"
2728
"github.com/arduino/arduino-cli/legacy/builder/constants"
@@ -306,6 +307,7 @@ func TestBuilderSketchWithOldLib(t *testing.T) {
306307
func TestBuilderSketchWithSubfolders(t *testing.T) {
307308
DownloadCoresAndToolsAndLibraries(t)
308309

310+
logrus.SetLevel(logrus.DebugLevel)
309311
ctx := prepareBuilderTestContext(t, paths.New("sketch_with_subfolders", "sketch_with_subfolders.ino"), "arduino:avr:uno")
310312

311313
buildPath := SetupBuildPath(t, ctx)

legacy/builder/utils/utils.go

Lines changed: 35 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,25 @@ func FilterFiles() filterFiles {
8787

8888
var SOURCE_CONTROL_FOLDERS = map[string]bool{"CVS": true, "RCS": true, ".git": true, ".github": true, ".svn": true, ".hg": true, ".bzr": true, ".vscode": true, ".settings": true, ".pioenvs": true, ".piolibdeps": true}
8989

90+
// FilterOutHiddenFiles is a ReadDirFilter that exclude files with a "." prefix in their name
91+
var FilterOutHiddenFiles = paths.FilterOutPrefixes(".")
92+
93+
// FilterOutSCCS is a ReadDirFilter that excludes known VSC or project files
94+
func FilterOutSCCS(file *paths.Path) bool {
95+
return !SOURCE_CONTROL_FOLDERS[file.Base()]
96+
}
97+
98+
// FilterReadableFiles is a ReadDirFilter that accepts only readable files
99+
func FilterReadableFiles(file *paths.Path) bool {
100+
// See if the file is readable by opening it
101+
f, err := file.Open()
102+
if err != nil {
103+
return false
104+
}
105+
f.Close()
106+
return true
107+
}
108+
90109
func IsSCCSOrHiddenFile(file os.FileInfo) bool {
91110
return IsSCCSFile(file) || IsHiddenFile(file)
92111
}
@@ -226,46 +245,22 @@ func AbsolutizePaths(files []string) ([]string, error) {
226245

227246
type CheckExtensionFunc func(ext string) bool
228247

229-
func FindFilesInFolder(files *[]string, folder string, extensions CheckExtensionFunc, recurse bool) error {
230-
walkFunc := func(path string, info os.FileInfo, err error) error {
231-
if err != nil {
232-
return err
233-
}
234-
235-
// Skip source control and hidden files and directories
236-
if IsSCCSOrHiddenFile(info) {
237-
if info.IsDir() {
238-
return filepath.SkipDir
239-
}
240-
return nil
241-
}
242-
243-
// Skip directories unless recurse is on, or this is the
244-
// root directory
245-
if info.IsDir() {
246-
if recurse || path == folder {
247-
return nil
248-
} else {
249-
return filepath.SkipDir
250-
}
251-
}
252-
253-
// Check (lowercased) extension against list of extensions
254-
if extensions != nil && !extensions(strings.ToLower(filepath.Ext(path))) {
255-
return nil
256-
}
257-
258-
// See if the file is readable by opening it
259-
currentFile, err := os.Open(path)
260-
if err != nil {
261-
return nil
262-
}
263-
currentFile.Close()
264-
265-
*files = append(*files, path)
266-
return nil
267-
}
268-
return gohasissues.Walk(folder, walkFunc)
248+
func FindFilesInFolder(dir *paths.Path, recurse bool, extensions []string) (paths.PathList, error) {
249+
fileFilter := paths.AndFilter(
250+
paths.FilterSuffixes(extensions...),
251+
FilterOutHiddenFiles,
252+
FilterOutSCCS,
253+
paths.FilterOutDirectories(),
254+
FilterReadableFiles,
255+
)
256+
if recurse {
257+
dirFilter := paths.AndFilter(
258+
FilterOutHiddenFiles,
259+
FilterOutSCCS,
260+
)
261+
return dir.ReadDirRecursiveFiltered(dirFilter, fileFilter)
262+
}
263+
return dir.ReadDir(fileFilter)
269264
}
270265

271266
func AppendIfNotPresent(target []string, elements ...string) []string {

0 commit comments

Comments
 (0)