Skip to content

Commit 3f9373a

Browse files
authored
[skip-changelog] legacy: removing a lot of duplicated/dead code (#2282)
* Replaced copyRecursive with go-paths library calls * Simplified download functions * Removed no more needed functions * Replaced some calls with go-paths library * Replaced some calls with go-paths library * Isolated some function into the (soon-to-be-removed) CMake generator This change will not break the CMake generator but will remove the CopyDir implementation from the public API space. * Removed now dead code * Moved md5 function to proper place * Refactor findAllFilesInFolder to use more go-paths function * Refactor findAllFilesInFolder to use more go-paths function * Made FilesAreOlderThan function to rationalize code * Yet another code-factorization of findAllFilesInFolder * Further simplified version of FilesAreOlderThan * Inlined CoreOrReferencedCoreHasChanged function * Inlined TXTBuildRulesHaveChanged function
1 parent f5a9b7c commit 3f9373a

9 files changed

+229
-575
lines changed

Diff for: legacy/builder/builder_utils/utils.go

+17-70
Original file line numberDiff line numberDiff line change
@@ -38,35 +38,30 @@ import (
3838

3939
var tr = i18n.Tr
4040

41-
func findAllFilesInFolder(sourcePath string, recurse bool) ([]string, error) {
42-
files, err := utils.ReadDirFiltered(sourcePath, utils.FilterFiles())
41+
// DirContentIsOlderThan returns true if the content of the given directory is
42+
// older than target file. If extensions are given, only the files with these
43+
// extensions are tested.
44+
func DirContentIsOlderThan(dir *paths.Path, target *paths.Path, extensions ...string) (bool, error) {
45+
targetStat, err := target.Stat()
4346
if err != nil {
44-
return nil, errors.WithStack(err)
45-
}
46-
var sources []string
47-
for _, file := range files {
48-
sources = append(sources, filepath.Join(sourcePath, file.Name()))
47+
return false, err
4948
}
49+
targetModTime := targetStat.ModTime()
5050

51-
if recurse {
52-
folders, err := utils.ReadDirFiltered(sourcePath, utils.FilterDirs)
51+
files, err := utils.FindFilesInFolder(dir, true, extensions...)
52+
if err != nil {
53+
return false, err
54+
}
55+
for _, file := range files {
56+
file, err := file.Stat()
5357
if err != nil {
54-
return nil, errors.WithStack(err)
58+
return false, err
5559
}
56-
57-
for _, folder := range folders {
58-
if !utils.IsSCCSOrHiddenFile(folder) {
59-
// Skip SCCS directories as they do not influence the build and can be very large
60-
otherSources, err := findAllFilesInFolder(filepath.Join(sourcePath, folder.Name()), recurse)
61-
if err != nil {
62-
return nil, errors.WithStack(err)
63-
}
64-
sources = append(sources, otherSources...)
65-
}
60+
if file.ModTime().After(targetModTime) {
61+
return false, nil
6662
}
6763
}
68-
69-
return sources, nil
64+
return true, nil
7065
}
7166

7267
func CompileFiles(ctx *types.Context, sourcePath *paths.Path, buildPath *paths.Path, buildProperties *properties.Map, includes []string) (paths.PathList, error) {
@@ -331,54 +326,6 @@ func removeEndingBackSlash(s string) string {
331326
return strings.TrimSuffix(s, "\\")
332327
}
333328

334-
func CoreOrReferencedCoreHasChanged(corePath, targetCorePath, targetFile *paths.Path) bool {
335-
336-
targetFileStat, err := targetFile.Stat()
337-
if err == nil {
338-
files, err := findAllFilesInFolder(corePath.String(), true)
339-
if err != nil {
340-
return true
341-
}
342-
for _, file := range files {
343-
fileStat, err := os.Stat(file)
344-
if err != nil || fileStat.ModTime().After(targetFileStat.ModTime()) {
345-
return true
346-
}
347-
}
348-
if targetCorePath != nil && !strings.EqualFold(corePath.String(), targetCorePath.String()) {
349-
return CoreOrReferencedCoreHasChanged(targetCorePath, nil, targetFile)
350-
}
351-
return false
352-
}
353-
return true
354-
}
355-
356-
func TXTBuildRulesHaveChanged(corePath, targetCorePath, targetFile *paths.Path) bool {
357-
358-
targetFileStat, err := targetFile.Stat()
359-
if err == nil {
360-
files, err := findAllFilesInFolder(corePath.String(), true)
361-
if err != nil {
362-
return true
363-
}
364-
for _, file := range files {
365-
// report changes only for .txt files
366-
if filepath.Ext(file) != ".txt" {
367-
continue
368-
}
369-
fileStat, err := os.Stat(file)
370-
if err != nil || fileStat.ModTime().After(targetFileStat.ModTime()) {
371-
return true
372-
}
373-
}
374-
if targetCorePath != nil && !corePath.EqualsTo(targetCorePath) {
375-
return TXTBuildRulesHaveChanged(targetCorePath, nil, targetFile)
376-
}
377-
return false
378-
}
379-
return true
380-
}
381-
382329
func ArchiveCompiledFiles(ctx *types.Context, buildPath *paths.Path, archiveFile *paths.Path, objectFilesToArchive paths.PathList, buildProperties *properties.Map) (*paths.Path, error) {
383330
archiveFilePath := buildPath.JoinPath(archiveFile)
384331

Diff for: legacy/builder/container_find_includes.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -427,7 +427,7 @@ func queueSourceFilesFromFolder(ctx *types.Context, sourceFileQueue *types.Uniqu
427427
for k := range globals.SourceFilesValidExtensions {
428428
sourceFileExtensions = append(sourceFileExtensions, k)
429429
}
430-
filePaths, err := utils.FindFilesInFolder(folder, recurse, sourceFileExtensions)
430+
filePaths, err := utils.FindFilesInFolder(folder, recurse, sourceFileExtensions...)
431431
if err != nil {
432432
return errors.WithStack(err)
433433
}

Diff for: legacy/builder/create_cmake_rule.go

+147-12
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ package builder
1717

1818
import (
1919
"fmt"
20+
"io"
21+
"os"
2022
"path/filepath"
2123
"regexp"
2224
"strings"
@@ -39,6 +41,130 @@ type ExportProjectCMake struct {
3941
var lineMatcher = regexp.MustCompile(`^#line\s\d+\s"`)
4042

4143
func (s *ExportProjectCMake) Run(ctx *types.Context) error {
44+
// copies the contents of the file named src to the file named
45+
// by dst. The file will be created if it does not already exist. If the
46+
// destination file exists, all it's contents will be replaced by the contents
47+
// of the source file. The file mode will be copied from the source and
48+
// the copied data is synced/flushed to stable storage.
49+
// TODO: Replace with call to go-paths-helper...
50+
copyFile := func(src, dst string) (err error) {
51+
in, err := os.Open(src)
52+
if err != nil {
53+
return
54+
}
55+
defer in.Close()
56+
57+
out, err := os.Create(dst)
58+
if err != nil {
59+
return
60+
}
61+
defer func() {
62+
if e := out.Close(); e != nil {
63+
err = e
64+
}
65+
}()
66+
67+
_, err = io.Copy(out, in)
68+
if err != nil {
69+
return
70+
}
71+
72+
err = out.Sync()
73+
if err != nil {
74+
return
75+
}
76+
77+
si, err := os.Stat(src)
78+
if err != nil {
79+
return
80+
}
81+
err = os.Chmod(dst, si.Mode())
82+
if err != nil {
83+
return
84+
}
85+
86+
return
87+
}
88+
89+
// recursively copies a directory tree, attempting to preserve permissions.
90+
// Source directory must exist, destination directory must *not* exist.
91+
// Symlinks are ignored and skipped.
92+
// TODO: Replace with call to go-paths-helper...
93+
var copyDir func(src string, dst string, extensions []string) (err error)
94+
copyDir = func(src string, dst string, extensions []string) (err error) {
95+
isAcceptedExtension := func(ext string) bool {
96+
ext = strings.ToLower(ext)
97+
for _, valid := range extensions {
98+
if ext == valid {
99+
return true
100+
}
101+
}
102+
return false
103+
}
104+
105+
src = filepath.Clean(src)
106+
dst = filepath.Clean(dst)
107+
108+
si, err := os.Stat(src)
109+
if err != nil {
110+
return err
111+
}
112+
if !si.IsDir() {
113+
return fmt.Errorf(tr("source is not a directory"))
114+
}
115+
116+
_, err = os.Stat(dst)
117+
if err != nil && !os.IsNotExist(err) {
118+
return
119+
}
120+
if err == nil {
121+
return fmt.Errorf(tr("destination already exists"))
122+
}
123+
124+
err = os.MkdirAll(dst, si.Mode())
125+
if err != nil {
126+
return
127+
}
128+
129+
entries, err := os.ReadDir(src)
130+
if err != nil {
131+
return
132+
}
133+
134+
for _, dirEntry := range entries {
135+
entry, scopeErr := dirEntry.Info()
136+
if scopeErr != nil {
137+
return
138+
}
139+
140+
srcPath := filepath.Join(src, entry.Name())
141+
dstPath := filepath.Join(dst, entry.Name())
142+
143+
if entry.IsDir() {
144+
err = copyDir(srcPath, dstPath, extensions)
145+
if err != nil {
146+
return
147+
}
148+
} else {
149+
// Skip symlinks.
150+
if entry.Mode()&os.ModeSymlink != 0 {
151+
continue
152+
}
153+
154+
if !isAcceptedExtension(filepath.Ext(srcPath)) {
155+
continue
156+
}
157+
158+
err = copyFile(srcPath, dstPath)
159+
if err != nil {
160+
return
161+
}
162+
}
163+
}
164+
165+
return
166+
}
167+
42168
var validExportExtensions = []string{".a", ".properties"}
43169
for ext := range globals.SourceFilesValidExtensions {
44170
validExportExtensions = append(validExportExtensions, ext)
@@ -76,7 +202,7 @@ func (s *ExportProjectCMake) Run(ctx *types.Context) error {
76202
// Copy used libraries in the correct folder
77203
libDir := libBaseFolder.Join(library.DirName)
78204
mcu := ctx.BuildProperties.Get(constants.BUILD_PROPERTIES_BUILD_MCU)
79-
utils.CopyDir(library.InstallDir.String(), libDir.String(), validExportExtensions)
205+
copyDir(library.InstallDir.String(), libDir.String(), validExportExtensions)
80206

81207
// Read cmake options if available
82208
isStaticLib := true
@@ -96,7 +222,7 @@ func (s *ExportProjectCMake) Run(ctx *types.Context) error {
96222
}
97223

98224
// Remove stray folders contining incompatible or not needed libraries archives
99-
files, _ := utils.FindFilesInFolder(libDir.Join("src"), true, validStaticLibExtensions)
225+
files, _ := utils.FindFilesInFolder(libDir.Join("src"), true, validStaticLibExtensions...)
100226
for _, file := range files {
101227
staticLibDir := file.Parent()
102228
if !isStaticLib || !strings.Contains(staticLibDir.String(), mcu) {
@@ -106,11 +232,11 @@ func (s *ExportProjectCMake) Run(ctx *types.Context) error {
106232
}
107233

108234
// Copy core + variant in use + preprocessed sketch in the correct folders
109-
err := utils.CopyDir(ctx.BuildProperties.Get("build.core.path"), coreFolder.String(), validExportExtensions)
235+
err := copyDir(ctx.BuildProperties.Get("build.core.path"), coreFolder.String(), validExportExtensions)
110236
if err != nil {
111237
fmt.Println(err)
112238
}
113-
err = utils.CopyDir(ctx.BuildProperties.Get("build.variant.path"), coreFolder.Join("variant").String(), validExportExtensions)
239+
err = copyDir(ctx.BuildProperties.Get("build.variant.path"), coreFolder.Join("variant").String(), validExportExtensions)
114240
if err != nil {
115241
fmt.Println(err)
116242
}
@@ -119,13 +245,13 @@ func (s *ExportProjectCMake) Run(ctx *types.Context) error {
119245
return err
120246
}
121247

122-
err = utils.CopyDir(ctx.SketchBuildPath.String(), cmakeFolder.Join("sketch").String(), validExportExtensions)
248+
err = copyDir(ctx.SketchBuildPath.String(), cmakeFolder.Join("sketch").String(), validExportExtensions)
123249
if err != nil {
124250
fmt.Println(err)
125251
}
126252

127253
// remove "#line 1 ..." from exported c_make folder sketch
128-
sketchFiles, _ := utils.FindFilesInFolder(cmakeFolder.Join("sketch"), false, validExportExtensions)
254+
sketchFiles, _ := utils.FindFilesInFolder(cmakeFolder.Join("sketch"), false, validExportExtensions...)
129255

130256
for _, file := range sketchFiles {
131257
input, err := file.ReadFile()
@@ -159,11 +285,11 @@ func (s *ExportProjectCMake) Run(ctx *types.Context) error {
159285
extractCompileFlags(ctx, "recipe.cpp.o.pattern", &defines, &dynamicLibsFromGccMinusL, &linkerflags, &linkDirectories)
160286

161287
// Extract folders with .h in them for adding in include list
162-
headerFiles, _ := utils.FindFilesInFolder(cmakeFolder, true, validHeaderExtensions)
288+
headerFiles, _ := utils.FindFilesInFolder(cmakeFolder, true, validHeaderExtensions...)
163289
foldersContainingHeaders := findUniqueFoldersRelative(headerFiles.AsStrings(), cmakeFolder.String())
164290

165291
// Extract folders with .a in them for adding in static libs paths list
166-
staticLibs, _ := utils.FindFilesInFolder(cmakeFolder, true, validStaticLibExtensions)
292+
staticLibs, _ := utils.FindFilesInFolder(cmakeFolder, true, validStaticLibExtensions...)
167293

168294
// Generate the CMakeLists global file
169295

@@ -232,25 +358,34 @@ func canExportCmakeProject(ctx *types.Context) bool {
232358
}
233359

234360
func extractCompileFlags(ctx *types.Context, recipe string, defines, dynamicLibs, linkerflags, linkDirectories *[]string) {
361+
appendIfNotPresent := func(target []string, elements ...string) []string {
362+
for _, element := range elements {
363+
if !slices.Contains(target, element) {
364+
target = append(target, element)
365+
}
366+
}
367+
return target
368+
}
369+
235370
command, _ := builder_utils.PrepareCommandForRecipe(ctx.BuildProperties, recipe, true, ctx.PackageManager.GetEnvVarsForSpawnedProcess())
236371

237372
for _, arg := range command.Args {
238373
if strings.HasPrefix(arg, "-D") {
239-
*defines = utils.AppendIfNotPresent(*defines, arg)
374+
*defines = appendIfNotPresent(*defines, arg)
240375
continue
241376
}
242377
if strings.HasPrefix(arg, "-l") {
243-
*dynamicLibs = utils.AppendIfNotPresent(*dynamicLibs, arg[2:])
378+
*dynamicLibs = appendIfNotPresent(*dynamicLibs, arg[2:])
244379
continue
245380
}
246381
if strings.HasPrefix(arg, "-L") {
247-
*linkDirectories = utils.AppendIfNotPresent(*linkDirectories, arg[2:])
382+
*linkDirectories = appendIfNotPresent(*linkDirectories, arg[2:])
248383
continue
249384
}
250385
if strings.HasPrefix(arg, "-") && !strings.HasPrefix(arg, "-I") && !strings.HasPrefix(arg, "-o") {
251386
// HACK : from linkerflags remove MMD (no cache is produced)
252387
if !strings.HasPrefix(arg, "-MMD") {
253-
*linkerflags = utils.AppendIfNotPresent(*linkerflags, arg)
388+
*linkerflags = appendIfNotPresent(*linkerflags, arg)
254389
}
255390
}
256391
}

0 commit comments

Comments
 (0)