forked from arduino/arduino-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
565 lines (499 loc) · 17.1 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
// This file is part of arduino-cli.
//
// Copyright 2020 ARDUINO SA (http://www.arduino.cc/)
//
// This software is released under the GNU General Public License version 3,
// which covers the main part of arduino-cli.
// The terms of this license can be found at:
// https://www.gnu.org/licenses/gpl-3.0.en.html
//
// You can be released from the requirements of the above licenses by purchasing
// a commercial license. Buying such a license is mandatory if you want to
// modify or otherwise use the software for commercial activities involving the
// Arduino software without disclosing the source code of your own applications.
// To purchase a commercial license, send an email to [email protected].
package builder_utils
import (
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"github.com/arduino/arduino-cli/i18n"
"github.com/arduino/arduino-cli/legacy/builder/constants"
"github.com/arduino/arduino-cli/legacy/builder/types"
"github.com/arduino/arduino-cli/legacy/builder/utils"
"github.com/arduino/go-paths-helper"
"github.com/arduino/go-properties-orderedmap"
"github.com/pkg/errors"
)
var tr = i18n.Tr
func PrintProgressIfProgressEnabledAndMachineLogger(ctx *types.Context) {
if !ctx.Progress.PrintEnabled {
return
}
log := ctx.GetLogger()
if log.Name() == "machine" {
log.Println(constants.LOG_LEVEL_INFO, tr("Progress {0}"), strconv.FormatFloat(float64(ctx.Progress.Progress), 'f', 2, 32))
}
}
func CompileFilesRecursive(ctx *types.Context, sourcePath *paths.Path, buildPath *paths.Path, buildProperties *properties.Map, includes []string) (paths.PathList, error) {
objectFiles, err := CompileFiles(ctx, sourcePath, false, buildPath, buildProperties, includes)
if err != nil {
return nil, errors.WithStack(err)
}
folders, err := utils.ReadDirFiltered(sourcePath.String(), utils.FilterDirs)
if err != nil {
return nil, errors.WithStack(err)
}
for _, folder := range folders {
subFolderObjectFiles, err := CompileFilesRecursive(ctx, sourcePath.Join(folder.Name()), buildPath.Join(folder.Name()), buildProperties, includes)
if err != nil {
return nil, errors.WithStack(err)
}
objectFiles.AddAll(subFolderObjectFiles)
}
return objectFiles, nil
}
func CompileFiles(ctx *types.Context, sourcePath *paths.Path, recurse bool, buildPath *paths.Path, buildProperties *properties.Map, includes []string) (paths.PathList, error) {
sSources, err := findFilesInFolder(sourcePath, ".S", recurse)
if err != nil {
return nil, errors.WithStack(err)
}
cSources, err := findFilesInFolder(sourcePath, ".c", recurse)
if err != nil {
return nil, errors.WithStack(err)
}
cppSources, err := findFilesInFolder(sourcePath, ".cpp", recurse)
if err != nil {
return nil, errors.WithStack(err)
}
ctx.Progress.AddSubSteps(len(sSources) + len(cSources) + len(cppSources))
defer ctx.Progress.RemoveSubSteps()
sObjectFiles, err := compileFilesWithRecipe(ctx, sourcePath, sSources, buildPath, buildProperties, includes, constants.RECIPE_S_PATTERN)
if err != nil {
return nil, errors.WithStack(err)
}
cObjectFiles, err := compileFilesWithRecipe(ctx, sourcePath, cSources, buildPath, buildProperties, includes, constants.RECIPE_C_PATTERN)
if err != nil {
return nil, errors.WithStack(err)
}
cppObjectFiles, err := compileFilesWithRecipe(ctx, sourcePath, cppSources, buildPath, buildProperties, includes, constants.RECIPE_CPP_PATTERN)
if err != nil {
return nil, errors.WithStack(err)
}
objectFiles := paths.NewPathList()
objectFiles.AddAll(sObjectFiles)
objectFiles.AddAll(cObjectFiles)
objectFiles.AddAll(cppObjectFiles)
return objectFiles, nil
}
func findFilesInFolder(sourcePath *paths.Path, extension string, recurse bool) (paths.PathList, error) {
files, err := utils.ReadDirFiltered(sourcePath.String(), utils.FilterFilesWithExtensions(extension))
if err != nil {
return nil, errors.WithStack(err)
}
var sources paths.PathList
for _, file := range files {
sources = append(sources, sourcePath.Join(file.Name()))
}
if recurse {
folders, err := utils.ReadDirFiltered(sourcePath.String(), utils.FilterDirs)
if err != nil {
return nil, errors.WithStack(err)
}
for _, folder := range folders {
otherSources, err := findFilesInFolder(sourcePath.Join(folder.Name()), extension, recurse)
if err != nil {
return nil, errors.WithStack(err)
}
sources = append(sources, otherSources...)
}
}
return sources, nil
}
func findAllFilesInFolder(sourcePath string, recurse bool) ([]string, error) {
files, err := utils.ReadDirFiltered(sourcePath, utils.FilterFiles())
if err != nil {
return nil, errors.WithStack(err)
}
var sources []string
for _, file := range files {
sources = append(sources, filepath.Join(sourcePath, file.Name()))
}
if recurse {
folders, err := utils.ReadDirFiltered(sourcePath, utils.FilterDirs)
if err != nil {
return nil, errors.WithStack(err)
}
for _, folder := range folders {
if !utils.IsSCCSOrHiddenFile(folder) {
// Skip SCCS directories as they do not influence the build and can be very large
otherSources, err := findAllFilesInFolder(filepath.Join(sourcePath, folder.Name()), recurse)
if err != nil {
return nil, errors.WithStack(err)
}
sources = append(sources, otherSources...)
}
}
}
return sources, nil
}
func compileFilesWithRecipe(ctx *types.Context, sourcePath *paths.Path, sources paths.PathList, buildPath *paths.Path, buildProperties *properties.Map, includes []string, recipe string) (paths.PathList, error) {
objectFiles := paths.NewPathList()
if len(sources) == 0 {
return objectFiles, nil
}
var objectFilesMux sync.Mutex
var errorsList []error
var errorsMux sync.Mutex
queue := make(chan *paths.Path)
job := func(source *paths.Path) {
objectFile, err := compileFileWithRecipe(ctx, sourcePath, source, buildPath, buildProperties, includes, recipe)
if err != nil {
errorsMux.Lock()
errorsList = append(errorsList, err)
errorsMux.Unlock()
} else {
objectFilesMux.Lock()
objectFiles.Add(objectFile)
objectFilesMux.Unlock()
}
}
// Spawn jobs runners
var wg sync.WaitGroup
jobs := ctx.Jobs
if jobs == 0 {
jobs = runtime.NumCPU()
}
for i := 0; i < jobs; i++ {
wg.Add(1)
go func() {
for source := range queue {
job(source)
}
wg.Done()
}()
}
// Feed jobs until error or done
for _, source := range sources {
errorsMux.Lock()
gotError := len(errorsList) > 0
errorsMux.Unlock()
if gotError {
break
}
queue <- source
ctx.Progress.CompleteStep()
PrintProgressIfProgressEnabledAndMachineLogger(ctx)
}
close(queue)
wg.Wait()
if len(errorsList) > 0 {
// output the first error
return nil, errors.WithStack(errorsList[0])
}
objectFiles.Sort()
return objectFiles, nil
}
func compileFileWithRecipe(ctx *types.Context, sourcePath *paths.Path, source *paths.Path, buildPath *paths.Path, buildProperties *properties.Map, includes []string, recipe string) (*paths.Path, error) {
logger := ctx.GetLogger()
properties := buildProperties.Clone()
properties.Set(constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS, properties.Get(constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS+"."+ctx.WarningsLevel))
properties.Set(constants.BUILD_PROPERTIES_INCLUDES, strings.Join(includes, constants.SPACE))
if len(ctx.Arduifines) > 0 {
properties.Set(constants.BUILD_PROPERTIES_INCLUDES, properties.Get(constants.BUILD_PROPERTIES_INCLUDES) + " " + ctx.Arduifines + " ")
}
properties.SetPath(constants.BUILD_PROPERTIES_SOURCE_FILE, source)
relativeSource, err := sourcePath.RelTo(source)
if err != nil {
return nil, errors.WithStack(err)
}
depsFile := buildPath.Join(relativeSource.String() + ".d")
objectFile := buildPath.Join(relativeSource.String() + ".o")
properties.SetPath(constants.BUILD_PROPERTIES_OBJECT_FILE, objectFile)
err = objectFile.Parent().MkdirAll()
if err != nil {
return nil, errors.WithStack(err)
}
objIsUpToDate, err := ObjFileIsUpToDate(ctx, source, objectFile, depsFile)
if err != nil {
return nil, errors.WithStack(err)
}
command, err := PrepareCommandForRecipe(properties, recipe, false)
if err != nil {
return nil, errors.WithStack(err)
}
if ctx.CompilationDatabase != nil {
ctx.CompilationDatabase.Add(source, command)
}
if !objIsUpToDate && !ctx.OnlyUpdateCompilationDatabase {
_, _, err = utils.ExecCommand(ctx, command, utils.ShowIfVerbose /* stdout */, utils.Show /* stderr */)
if err != nil {
return nil, errors.WithStack(err)
}
} else if ctx.Verbose {
if objIsUpToDate {
logger.Println(constants.LOG_LEVEL_INFO, tr("Using previously compiled file: {0}"), objectFile)
} else {
logger.Println("info", tr("Skipping compile of: {0}"), objectFile)
}
}
return objectFile, nil
}
func ObjFileIsUpToDate(ctx *types.Context, sourceFile, objectFile, dependencyFile *paths.Path) (bool, error) {
logger := ctx.GetLogger()
debugLevel := ctx.DebugLevel
if debugLevel >= 20 {
logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("Checking previous results for {0} (result = {1}, dep = {2})"), sourceFile, objectFile, dependencyFile)
}
if objectFile == nil || dependencyFile == nil {
if debugLevel >= 20 {
logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("Not found: nil"))
}
return false, nil
}
sourceFile = sourceFile.Clean()
sourceFileStat, err := sourceFile.Stat()
if err != nil {
return false, errors.WithStack(err)
}
objectFile = objectFile.Clean()
objectFileStat, err := objectFile.Stat()
if err != nil {
if os.IsNotExist(err) {
if debugLevel >= 20 {
logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("Not found: {0}"), objectFile)
}
return false, nil
} else {
return false, errors.WithStack(err)
}
}
dependencyFile = dependencyFile.Clean()
dependencyFileStat, err := dependencyFile.Stat()
if err != nil {
if os.IsNotExist(err) {
if debugLevel >= 20 {
logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("Not found: {0}"), dependencyFile)
}
return false, nil
} else {
return false, errors.WithStack(err)
}
}
if sourceFileStat.ModTime().After(objectFileStat.ModTime()) {
if debugLevel >= 20 {
logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("{0} newer than {1}"), sourceFile, objectFile)
}
return false, nil
}
if sourceFileStat.ModTime().After(dependencyFileStat.ModTime()) {
if debugLevel >= 20 {
logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("{0} newer than {1}"), sourceFile, dependencyFile)
}
return false, nil
}
rows, err := dependencyFile.ReadFileAsLines()
if err != nil {
return false, errors.WithStack(err)
}
rows = utils.Map(rows, removeEndingBackSlash)
rows = utils.Map(rows, strings.TrimSpace)
rows = utils.Map(rows, unescapeDep)
rows = utils.Filter(rows, nonEmptyString)
if len(rows) == 0 {
return true, nil
}
firstRow := rows[0]
if !strings.HasSuffix(firstRow, ":") {
if debugLevel >= 20 {
logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("No colon in first line of depfile"))
}
return false, nil
}
objFileInDepFile := firstRow[:len(firstRow)-1]
if objFileInDepFile != objectFile.String() {
if debugLevel >= 20 {
logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("Depfile is about different file: {0}"), objFileInDepFile)
}
return false, nil
}
// The first line of the depfile contains the path to the object file to generate.
// The second line of the depfile contains the path to the source file.
// All subsequent lines contain the header files necessary to compile the object file.
// If we don't do this check it might happen that trying to compile a source file
// that has the same name but a different path wouldn't recreate the object file.
if sourceFile.String() != strings.Trim(rows[1], " ") {
return false, nil
}
rows = rows[1:]
for _, row := range rows {
depStat, err := os.Stat(row)
if err != nil && !os.IsNotExist(err) {
// There is probably a parsing error of the dep file
// Ignore the error and trigger a full rebuild anyway
if debugLevel >= 20 {
logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("Failed to read: {0}"), row)
logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, err.Error())
}
return false, nil
}
if os.IsNotExist(err) {
if debugLevel >= 20 {
logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("Not found: {0}"), row)
}
return false, nil
}
if depStat.ModTime().After(objectFileStat.ModTime()) {
if debugLevel >= 20 {
logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("{0} newer than {1}"), row, objectFile)
}
return false, nil
}
}
return true, nil
}
func unescapeDep(s string) string {
s = strings.Replace(s, "\\ ", " ", -1)
s = strings.Replace(s, "\\\t", "\t", -1)
s = strings.Replace(s, "\\#", "#", -1)
s = strings.Replace(s, "$$", "$", -1)
s = strings.Replace(s, "\\\\", "\\", -1)
return s
}
func removeEndingBackSlash(s string) string {
if strings.HasSuffix(s, "\\") {
s = s[:len(s)-1]
}
return s
}
func nonEmptyString(s string) bool {
return s != constants.EMPTY_STRING
}
func CoreOrReferencedCoreHasChanged(corePath, targetCorePath, targetFile *paths.Path) bool {
targetFileStat, err := targetFile.Stat()
if err == nil {
files, err := findAllFilesInFolder(corePath.String(), true)
if err != nil {
return true
}
for _, file := range files {
fileStat, err := os.Stat(file)
if err != nil || fileStat.ModTime().After(targetFileStat.ModTime()) {
return true
}
}
if targetCorePath != nil && !strings.EqualFold(corePath.String(), targetCorePath.String()) {
return CoreOrReferencedCoreHasChanged(targetCorePath, nil, targetFile)
}
return false
}
return true
}
func TXTBuildRulesHaveChanged(corePath, targetCorePath, targetFile *paths.Path) bool {
targetFileStat, err := targetFile.Stat()
if err == nil {
files, err := findAllFilesInFolder(corePath.String(), true)
if err != nil {
return true
}
for _, file := range files {
// report changes only for .txt files
if filepath.Ext(file) != ".txt" {
continue
}
fileStat, err := os.Stat(file)
if err != nil || fileStat.ModTime().After(targetFileStat.ModTime()) {
return true
}
}
if targetCorePath != nil && !corePath.EqualsTo(targetCorePath) {
return TXTBuildRulesHaveChanged(targetCorePath, nil, targetFile)
}
return false
}
return true
}
func ArchiveCompiledFiles(ctx *types.Context, buildPath *paths.Path, archiveFile *paths.Path, objectFilesToArchive paths.PathList, buildProperties *properties.Map) (*paths.Path, error) {
logger := ctx.GetLogger()
archiveFilePath := buildPath.JoinPath(archiveFile)
if ctx.OnlyUpdateCompilationDatabase {
if ctx.Verbose {
logger.Println("info", tr("Skipping archive creation of: {0}"), archiveFilePath)
}
return archiveFilePath, nil
}
if archiveFileStat, err := archiveFilePath.Stat(); err == nil {
rebuildArchive := false
for _, objectFile := range objectFilesToArchive {
objectFileStat, err := objectFile.Stat()
if err != nil || objectFileStat.ModTime().After(archiveFileStat.ModTime()) {
// need to rebuild the archive
rebuildArchive = true
break
}
}
// something changed, rebuild the core archive
if rebuildArchive {
if err := archiveFilePath.Remove(); err != nil {
return nil, errors.WithStack(err)
}
} else {
if ctx.Verbose {
logger.Println(constants.LOG_LEVEL_INFO, tr("Using previously compiled file: {0}"), archiveFilePath)
}
return archiveFilePath, nil
}
}
for _, objectFile := range objectFilesToArchive {
properties := buildProperties.Clone()
properties.Set(constants.BUILD_PROPERTIES_ARCHIVE_FILE, archiveFilePath.Base())
properties.SetPath(constants.BUILD_PROPERTIES_ARCHIVE_FILE_PATH, archiveFilePath)
properties.SetPath(constants.BUILD_PROPERTIES_OBJECT_FILE, objectFile)
command, err := PrepareCommandForRecipe(properties, constants.RECIPE_AR_PATTERN, false)
if err != nil {
return nil, errors.WithStack(err)
}
_, _, err = utils.ExecCommand(ctx, command, utils.ShowIfVerbose /* stdout */, utils.Show /* stderr */)
if err != nil {
return nil, errors.WithStack(err)
}
}
return archiveFilePath, nil
}
const COMMANDLINE_LIMIT = 30000
func PrepareCommandForRecipe(buildProperties *properties.Map, recipe string, removeUnsetProperties bool) (*exec.Cmd, error) {
pattern := buildProperties.Get(recipe)
if pattern == "" {
return nil, errors.Errorf(tr("%s pattern is missing"), recipe)
}
commandLine := buildProperties.ExpandPropsInString(pattern)
if removeUnsetProperties {
commandLine = properties.DeleteUnexpandedPropsFromString(commandLine)
}
parts, err := properties.SplitQuotedString(commandLine, `"'`, false)
if err != nil {
return nil, errors.WithStack(err)
}
command := exec.Command(parts[0], parts[1:]...)
// if the overall commandline is too long for the platform
// try reducing the length by making the filenames relative
// and changing working directory to build.path
if len(commandLine) > COMMANDLINE_LIMIT {
relativePath := buildProperties.Get("build.path")
for i, arg := range command.Args {
if _, err := os.Stat(arg); os.IsNotExist(err) {
continue
}
rel, err := filepath.Rel(relativePath, arg)
if err == nil && !strings.Contains(rel, "..") && len(rel) < len(arg) {
command.Args[i] = rel
}
}
command.Dir = relativePath
}
return command, nil
}