/
manifest_parser.go
1715 lines (1461 loc) · 49.4 KB
/
manifest_parser.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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) 2014-2019 Cesanta Software Limited
// All rights reserved
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//go:generate go-bindata-assetfs -pkg manifest_parser -nocompress -modtime 1 -mode 420 data/
// Check README.md for detailed explanation of parsing steps, limitations etc.
package manifest_parser
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"text/template"
"time"
"github.com/golang/glog"
"github.com/juju/errors"
flag "github.com/spf13/pflag"
yaml "gopkg.in/yaml.v2"
"github.com/mongoose-os/mos/cli/build"
moscommon "github.com/mongoose-os/mos/cli/common"
"github.com/mongoose-os/mos/cli/interpreter"
"github.com/mongoose-os/mos/cli/ourutil"
"github.com/mongoose-os/mos/version"
)
const (
// Manifest version changes:
//
// - 2017-06-03: added support for @all_libs in filesystem and sources
// - 2017-06-16: added support for conds with very basic expressions
// (only build_vars)
// - 2017-09-29: added support for includes
// - 2018-06-12: added support for globs in init_deps
// - 2018-06-20: added no_implicit_init_deps
// - 2018-08-13: added support for non-GitHub Git repos
// - 2018-08-29: added support for adding libs under conds
// - 2018-09-24: added special handling of the "boards" lib
// - 2019-04-26: added warning and error
// - 2019-07-28: added init_before
// - 2020-01-21: added ability to override lib variants from conds in app manifest
// - 2020-01-29: added ability to override app name, description and version from app's conds
minManifestVersion = "2017-03-17"
maxManifestVersion = "2020-01-29"
depsApp = "app"
allLibsKeyword = "@all_libs"
assetPrefix = "asset://"
rootManifestAssetName = "data/root_manifest.yml"
coreLibName = "core"
coreLibLocation = "https://github.com/mongoose-os-libs/core"
supportedPlatforms = "cc3200 cc3220 esp32 esp8266 rs14100 stm32 ubuntu"
)
var (
sourceGlobs = flag.StringSlice("source-glob", []string{"*.c", "*.cpp"}, "glob to use for source dirs. Can be used multiple times.")
)
type ComponentProvider interface {
// GetLibLocalPath returns local path to the given software module.
// NOTE that this method can be called concurrently for different modules.
GetLibLocalPath(
m *build.SWModule, rootAppDir, libsDefVersion, platform string,
) (string, error)
GetModuleLocalPath(
m *build.SWModule, rootAppDir, modulesDefVersion, platform string,
) (string, error)
GetMongooseOSLocalPath(rootAppDir, mongooseOSVersion string) (string, error)
}
type ReadManifestCallbacks struct {
ComponentProvider ComponentProvider
}
// Last-minute adjustments for the manifest, typically constructed from command
// line
type ManifestAdjustments struct {
Platform string
BuildVars map[string]string
CDefs map[string]string
CFlags []string
CXXFlags []string
ExtraLibs []build.SWModule
}
type RMFOut struct {
MTime time.Time
MosDirEffective string
AppSourceDirs []string
AppFSDirs []string
AppBinLibDirs []string
}
type libPrepareResult struct {
mtime time.Time
err error
}
func ReadManifestFinal(
dir string, adjustments *ManifestAdjustments,
logWriter io.Writer, interp *interpreter.MosInterpreter,
cbs *ReadManifestCallbacks,
requireArch, preferPrebuiltLibs bool,
binaryLibsUpdateInterval time.Duration,
) (*build.FWAppManifest, *RMFOut, error) {
interp = interp.Copy()
if adjustments == nil {
adjustments = &ManifestAdjustments{}
}
fp := &RMFOut{}
buildDirAbs, err := filepath.Abs(moscommon.GetBuildDir(dir))
if err != nil {
return nil, nil, errors.Trace(err)
}
manifest, mtime, err := readManifestWithLibs(
dir, adjustments, logWriter, interp, cbs, requireArch,
)
if err != nil {
return nil, nil, errors.Trace(err)
}
// Set the mos.platform variable
interp.MVars.SetVar(interpreter.GetMVarNameMosPlatform(), manifest.Platform)
if err := interpreter.SetManifestVars(interp.MVars, manifest); err != nil {
return nil, nil, errors.Trace(err)
}
// Prepare local copies of all sw modules {{{
for _, m := range manifest.Modules {
name, err := m.GetName()
if err != nil {
return nil, nil, errors.Trace(err)
}
moduleDir, err := cbs.ComponentProvider.GetModuleLocalPath(&m, dir, manifest.ModulesVersion, manifest.Platform)
if err != nil {
return nil, nil, errors.Trace(err)
}
interpreter.SetModuleVars(interp.MVars, name, moduleDir)
}
// }}}
// Determine mongoose-os dir (fp.MosDirEffective) {{{
fp.MosDirEffective, err = cbs.ComponentProvider.GetMongooseOSLocalPath(
dir, manifest.MongooseOsVersion,
)
if err != nil {
return nil, nil, errors.Trace(err)
}
fp.MosDirEffective, err = filepath.Abs(fp.MosDirEffective)
if err != nil {
return nil, nil, errors.Annotatef(err, "getting absolute path of %q", fp.MosDirEffective)
}
interpreter.SetModuleVars(interp.MVars, "mongoose-os", fp.MosDirEffective)
// }}}
// Get sources and filesystem files from the manifest, expanding expressions {{{
manifest.Sources, err = interpreter.ExpandVarsSlice(interp, manifest.Sources, false)
if err != nil {
return nil, nil, errors.Trace(err)
}
for k, v := range manifest.LibsHandled {
manifest.LibsHandled[k].Sources, err = interpreter.ExpandVarsSlice(interp, v.Sources, false)
if err != nil {
return nil, nil, errors.Trace(err)
}
}
manifest.Includes, err = interpreter.ExpandVarsSlice(interp, manifest.Includes, false)
if err != nil {
return nil, nil, errors.Trace(err)
}
// AppSourceDirs will be populated later, needed to mount those paths to the
// docker container
fp.AppSourceDirs = []string{}
manifest.Filesystem, err = interpreter.ExpandVarsSlice(interp, manifest.Filesystem, false)
if err != nil {
return nil, nil, errors.Trace(err)
}
manifest.BinaryLibs, err = interpreter.ExpandVarsSlice(interp, manifest.BinaryLibs, false)
if err != nil {
return nil, nil, errors.Trace(err)
}
manifest.Tests, err = interpreter.ExpandVarsSlice(interp, manifest.Tests, false)
if err != nil {
return nil, nil, errors.Trace(err)
}
manifest.Sources = prependPaths(manifest.Sources, dir)
manifest.Includes = prependPaths(manifest.Includes, dir)
manifest.Filesystem = prependPaths(manifest.Filesystem, dir)
manifest.BinaryLibs = prependPaths(manifest.BinaryLibs, dir)
manifest.Tests = prependPaths(manifest.Tests, dir)
// }}}
if manifest.Type == build.AppTypeApp {
// Generate deps_init C code, and if it's not empty, write it to the temp
// file and add to sources
depsCCode, err := getDepsInitCCode(manifest)
if err != nil {
return nil, nil, errors.Trace(err)
}
if len(depsCCode) != 0 {
fname := moscommon.GetDepsInitCFilePath(buildDirAbs)
if err := os.MkdirAll(moscommon.GetGeneratedFilesDir(buildDirAbs), 0777); err != nil {
return nil, nil, errors.Trace(err)
}
if err = ioutil.WriteFile(fname, depsCCode, 0666); err != nil {
return nil, nil, errors.Trace(err)
}
// The modification time of autogenerated file should be set to that of
// the manifest itself, so that make handles dependencies correctly.
if err := os.Chtimes(fname, mtime, mtime); err != nil {
return nil, nil, errors.Trace(err)
}
manifest.Sources = append(manifest.Sources, fname)
}
}
// Convert manifest.Sources into paths to concrete existing source files.
manifest.Sources, fp.AppSourceDirs, err = resolvePaths(manifest.Sources, *sourceGlobs)
if err != nil {
return nil, nil, errors.Trace(err)
}
manifest.Filesystem, fp.AppFSDirs, err = resolvePaths(manifest.Filesystem, []string{"*"})
if err != nil {
return nil, nil, errors.Trace(err)
}
// When building an app, also add all libs' sources or prebuilt binaries.
if manifest.Type == build.AppTypeApp {
for k, lcur := range manifest.LibsHandled {
libSourceDirs := []string{}
origSources := lcur.Sources
// Convert dirs and globs to actual files
manifest.LibsHandled[k].Sources, libSourceDirs, err = resolvePaths(lcur.Sources, *sourceGlobs)
if err != nil {
return nil, nil, errors.Trace(err)
}
// Check if binary version of the lib exists. We do this if there are
// no sources or if we prefer binary libs (for speed).
binaryLib := ""
var fetchErrs []error
if (len(manifest.LibsHandled[k].Sources) == 0 && len(origSources) != 0) || preferPrebuiltLibs {
var variants []string
if lcur.Lib.Variant != "" {
variants = append(variants, lcur.Lib.Variant)
}
libVersion := lcur.Lib.GetVersion(manifest.LibsVersion)
if v, ok := interp.MVars.GetVar("build_vars.BOARD"); ok && v.(string) != "" {
variants = append(variants, fmt.Sprintf("%s-%s", manifest.Platform, v.(string)))
}
variants = append(variants, manifest.Platform)
for _, variant := range variants {
bl := moscommon.GetBinaryLibFilePath(buildDirAbs, lcur.Lib.Name, variant, libVersion)
fi, err := os.Stat(bl)
if err == nil {
// Local file exists, check it.
// We want to re-fetch "latest" libs regularly (same way as repos get pulled).
if libVersion != version.LatestVersionName || binaryLibsUpdateInterval == 0 ||
fi.ModTime().Add(binaryLibsUpdateInterval).After(time.Now()) {
if fi.Size() == 0 {
// It's a tombstone, meaning this variant does not exist. Skip it.
glog.V(1).Infof("%s is a tombstone, skipping", bl)
continue
}
bl, err := filepath.Abs(bl)
if err != nil {
return nil, nil, errors.Trace(err)
}
ourutil.Freportf(logWriter, "Prebuilt binary for %q already exists at %q", lcur.Lib.Name, bl)
binaryLib = bl
break
}
}
// Try fetching
fetchErr := lcur.Lib.FetchPrebuiltBinary(variant, libVersion, bl)
if fetchErr == nil {
ourutil.Freportf(logWriter, "Successfully fetched prebuilt binary for %q to %q", lcur.Lib.Name, bl)
binaryLib = bl
} else {
fetchErrs = append(fetchErrs, fetchErr)
if os.IsNotExist(errors.Cause(fetchErr)) {
// This variant does not exist, create a tombstone to avoid fetching in the future.
glog.V(1).Infof("%s: creating a tombstone", bl)
ioutil.WriteFile(bl, nil, 0664)
}
}
if binaryLib != "" {
break
}
}
}
if binaryLib != "" {
// We should use binary lib instead of sources
manifest.LibsHandled[k].Sources = []string{}
manifest.BinaryLibs = append(manifest.BinaryLibs, binaryLib)
} else {
// Use lib sources, not prebuilt binary
if len(manifest.LibsHandled[k].Sources) == 0 && len(origSources) != 0 {
// Originally the lib had some sources in its mos.yml, but turns out
// that they don't exist (closed source lib), and we have failed to fetch a prebuilt
// binary for it. Error out with a descriptive message.
return nil, nil, errors.Errorf(
"neither sources nor prebuilt binary exists for the lib %q "+
"(or, if a library doesn't have any code by design, its mos.yml "+
"shouldn't contain \"sources\"). Fetch error was: %s",
manifest.LibsHandled[k].Lib.Name, fetchErrs,
)
}
manifest.Sources = append(manifest.Sources, manifest.LibsHandled[k].Sources...)
}
fp.AppSourceDirs = append(fp.AppSourceDirs, libSourceDirs...)
}
}
manifest.BinaryLibs, fp.AppBinLibDirs, err = resolvePaths(manifest.BinaryLibs, []string{"*.a"})
if err != nil {
return nil, nil, errors.Trace(err)
}
manifest.Tests, _, err = resolvePaths(manifest.Tests, []string{"*"})
if err != nil {
return nil, nil, errors.Trace(err)
}
allPlatforms, err := getAllSupportedPlatforms(fp.MosDirEffective)
if err != nil {
return nil, nil, errors.Trace(err)
}
manifest.Platforms = mergeSupportedPlatforms(manifest.Platforms, allPlatforms)
sort.Strings(manifest.Platforms)
fp.MTime = mtime
return manifest, fp, nil
}
var libsAddedError = errors.Errorf("new libs added")
type prepareLibsEntry struct {
parentNodeName string
manifest *build.FWAppManifest
}
type manifestParseContext struct {
// Directory of the "root" app. Might be a temporary directory.
rootAppDir string
adjustments ManifestAdjustments
logWriter io.Writer
deps *Deps
initDeps *Deps
libsHandled map[string]*build.FWAppManifestLibHandled
appManifest *build.FWAppManifest
interp *interpreter.MosInterpreter
cbs *ReadManifestCallbacks
requireArch bool
prepareLibs []*prepareLibsEntry
mtx *sync.Mutex
flagSet *stringFlagSet
}
// readManifestWithLibs reads manifest from the provided dir, "expands" all
// libs (so that the returned manifest does not really contain any libs),
// and also returns the most recent modification time of all encountered
// manifests.
func readManifestWithLibs(
dir string, adjustments *ManifestAdjustments,
logWriter io.Writer, interp *interpreter.MosInterpreter,
cbs *ReadManifestCallbacks,
requireArch bool,
) (*build.FWAppManifest, time.Time, error) {
interp = interp.Copy()
libsHandled := map[string]*build.FWAppManifestLibHandled{}
// Create a deps structure and add a root node: an "app"
deps := NewDeps()
deps.AddNode(depsApp)
initDeps := NewDeps()
initDeps.AddNode(depsApp)
pc := &manifestParseContext{
rootAppDir: dir,
adjustments: *adjustments,
logWriter: logWriter,
deps: deps,
initDeps: initDeps,
libsHandled: libsHandled,
appManifest: nil,
interp: interp,
requireArch: requireArch,
cbs: cbs,
mtx: &sync.Mutex{},
flagSet: newStringFlagSet(),
}
manifest, mtime, err := readManifestWithLibs2(depsApp, dir, pc)
if err != nil {
return nil, time.Time{}, errors.Trace(err)
}
// Set the mos.platform variable
interp.MVars.SetVar(interpreter.GetMVarNameMosPlatform(), manifest.Platform)
pass := 0
for {
for len(pc.prepareLibs) != 0 {
pass++
glog.Infof("Prepare libs pass %d (%d)", pass, len(pc.prepareLibs))
pll := pc.prepareLibs
pc.prepareLibs = nil
for _, ple := range pll {
libsMtime, err := prepareLibs(ple.parentNodeName, ple.manifest, pc)
if err != nil {
return nil, time.Time{}, errors.Trace(err)
} else {
if libsMtime.After(mtime) {
mtime = libsMtime
}
}
}
}
// Get all deps in topological order
depsTopo, cycle := deps.Topological(true)
if cycle != nil {
return nil, time.Time{}, errors.Errorf(
"dependency cycle: %v", strings.Join(cycle, " -> "),
)
}
// Remove the last item from topo, which is depsApp
//
// TODO(dfrank): it would be nice to handle an app just another dependency
// and generate init code for it, but it would be a breaking change, at least
// because all libs init functions return bool, but mgos_app_init returns
// enum mgos_app_init_result.
depsTopo = depsTopo[0 : len(depsTopo)-1]
lhp := map[string]*build.FWAppManifestLibHandled{}
for k, v := range libsHandled {
vc := *v
lhp[k] = &vc
}
// Expand initDeps (which may contain globs) against actual list of libs.
initDepsExpanded := NewDeps()
expandGlob := func(dep string, res *[]string) {
deps:
for _, d := range depsTopo {
if m, _ := path.Match(dep, d); m {
for _, rd := range *res {
if d == rd {
continue deps
}
}
*res = append(*res, d)
}
}
return
}
for _, node := range initDeps.GetNodes() {
if node == depsApp {
continue
}
// Expand globs in keys (intorduced by init_before)
var nodeExpanded []string
expandGlob(node, &nodeExpanded)
if !(len(nodeExpanded) == 1 && nodeExpanded[0] == node) {
glog.V(1).Infof("%s expanded to %s", node, nodeExpanded)
}
nodeDeps := initDeps.GetDeps(node)
// Expand globs in values (introduced by init_after)
var nodeDepsExpanded []string
for _, nd := range nodeDeps {
expandGlob(nd, &nodeDepsExpanded)
}
for _, ne := range nodeExpanded {
initDepsExpanded.AddNodeWithDeps(ne, nodeDepsExpanded)
}
}
for _, node := range initDepsExpanded.GetNodes() {
nodeDepsExpanded := initDepsExpanded.GetDeps(node)
sort.Strings(nodeDepsExpanded)
glog.V(1).Infof("%s init deps: %s", node, nodeDepsExpanded)
lhp[node].InitDeps = nodeDepsExpanded
}
initDepsTopo, cycle := initDepsExpanded.Topological(true)
if cycle != nil {
return nil, time.Time{}, errors.Errorf(
"init dependency cycle: %v", strings.Join(cycle, " -> "),
)
}
manifest.InitDeps = initDepsTopo
// Create a LibsHandled slice in topological order computed above
manifest.LibsHandled = make([]build.FWAppManifestLibHandled, 0, len(depsTopo))
for _, v := range depsTopo {
manifest.LibsHandled = append(manifest.LibsHandled, *lhp[v])
}
var lhNames []string
for _, lh := range manifest.LibsHandled {
lhn, _ := lh.Lib.GetName()
lhNames = append(lhNames, lhn)
}
glog.Infof("libs_handled: %s", lhNames)
glog.Infof("init_deps: %s", manifest.InitDeps)
if err := expandManifestLibsAndConds(manifest, interp, adjustments); err != nil {
if errors.Cause(err) == libsAddedError {
if len(manifest.Libs) > 0 {
libsMtime, err := prepareLibs(depsApp, manifest, pc)
if err != nil {
return nil, time.Time{}, errors.Trace(err)
}
if libsMtime.After(mtime) {
mtime = libsMtime
}
}
for _, lh := range manifest.LibsHandled {
if len(lh.Manifest.Libs) > 0 {
libsMtime, err := prepareLibs(lh.Lib.Name, lh.Manifest, pc)
if err != nil {
return nil, time.Time{}, errors.Trace(err)
}
if libsMtime.After(mtime) {
mtime = libsMtime
}
}
}
continue
}
return nil, time.Time{}, errors.Trace(err)
}
if err := expandManifestAllLibsPaths(manifest); err != nil {
return nil, time.Time{}, errors.Trace(err)
}
break
}
return manifest, mtime, nil
}
func readManifestWithLibs2(parentNodeName, dir string, pc *manifestParseContext) (*build.FWAppManifest, time.Time, error) {
manifest, mtime, err := ReadManifest(dir, &pc.adjustments, pc.interp)
if err != nil {
return nil, time.Time{}, errors.Trace(err)
}
pc.mtx.Lock()
defer pc.mtx.Unlock()
if pc.requireArch && manifest.Platform == "" {
return nil, time.Time{}, errors.Errorf("--platform must be specified or mos.yml should contain a platform key")
}
// If the given appManifest is nil, it means that we've just read one, so
// remember it as such
if pc.appManifest == nil {
pc.appManifest = manifest
// Also, remove any build vars from adjustments, so that they won't be set on
// deps' manifest we're going to read as well
pc.adjustments.BuildVars = nil
if !manifest.NoImplInitDeps {
found := false
for _, l := range manifest.Libs {
l.Normalize()
if name, _ := l.GetName(); name == coreLibName {
found = true
break
}
}
if !found {
glog.Infof("Inserted core lib")
manifest.Libs = append(manifest.Libs, build.SWModule{
Location: coreLibLocation,
})
}
}
for _, l := range pc.adjustments.ExtraLibs {
manifest.Libs = append(manifest.Libs, l)
}
pc.adjustments.ExtraLibs = nil
manifest.BuildVars["MGOS"] = "1"
manifest.CDefs["MGOS"] = "1"
for k, v := range pc.adjustments.CDefs {
manifest.CDefs[k] = v
}
manifest.CFlags = append(manifest.CFlags, pc.adjustments.CFlags...)
pc.adjustments.CFlags = nil
manifest.CXXFlags = append(manifest.CXXFlags, pc.adjustments.CXXFlags...)
pc.adjustments.CXXFlags = nil
// Apply vars from the app manifest.
// Since this we are at the top level, we can do it right now.
interpreter.SetManifestVars(pc.interp.MVars, manifest)
}
pc.prepareLibs = append(pc.prepareLibs, &prepareLibsEntry{
parentNodeName: parentNodeName,
manifest: manifest,
})
return manifest, mtime, err
}
func prepareLibs(parentNodeName string, manifest *build.FWAppManifest, pc *manifestParseContext) (time.Time, error) {
wg := &sync.WaitGroup{}
wg.Add(len(manifest.Libs))
lpres := make(chan libPrepareResult)
for i := range manifest.Libs {
go prepareLib(parentNodeName, &manifest.Libs[i], manifest, pc, lpres, wg)
}
// Closer goroutine
go func() {
wg.Wait()
close(lpres)
}()
// Handle all lib prepare results
var mtime time.Time
for res := range lpres {
if res.err != nil {
return time.Time{}, errors.Trace(res.err)
}
// We should return the latest modification date of all encountered
// manifests, so let's see if we got the later mtime here
if res.mtime.After(mtime) {
mtime = res.mtime
}
}
manifest.Libs = nil
return mtime, nil
}
func prepareLib(
parentNodeName string, m *build.SWModule,
manifest *build.FWAppManifest,
pc *manifestParseContext,
lpres chan libPrepareResult,
wg *sync.WaitGroup,
) {
defer wg.Done()
if err := m.Normalize(); err != nil {
lpres <- libPrepareResult{
err: errors.Trace(err),
}
return
}
name, err := m.GetName()
if err != nil {
lpres <- libPrepareResult{
err: errors.Trace(err),
}
return
}
pc.mtx.Lock()
pc.deps.AddDep(parentNodeName, name)
if !manifest.NoImplInitDeps {
pc.initDeps.AddDep(parentNodeName, name) // Implicit init dep
}
if !pc.flagSet.Add(name) {
if pc.libsHandled[name] != nil {
// That library is already handled by someone else
// App manifest can override library variants (in conds).
lm := &pc.libsHandled[name].Lib
if m.Variant != "" && parentNodeName == depsApp {
glog.V(1).Infof("%s variant: %q -> %q", name, lm.Variant, m.Variant)
lm.Variant = m.Variant
}
} else {
lpres <- libPrepareResult{
err: fmt.Errorf("duplicate library %q in %s", name, manifest.Origin),
}
}
pc.mtx.Unlock()
return
}
pc.mtx.Unlock()
ourutil.Freportf(pc.logWriter, "Handling lib %q...", name)
libLocalDir, err := pc.cbs.ComponentProvider.GetLibLocalPath(
m, pc.rootAppDir, pc.appManifest.LibsVersion, manifest.Platform,
)
if err != nil {
lpres <- libPrepareResult{
err: errors.Trace(err),
}
return
}
libLocalDir, err = filepath.Abs(libLocalDir)
if err != nil {
lpres <- libPrepareResult{
err: errors.Trace(err),
}
return
}
// Now that we know we need to handle current lib, add a node for it
pc.mtx.Lock()
pc.deps.AddNode(name)
pc.initDeps.AddNode(name)
// If platform is empty, we need to set it from the outer manifest,
// because arch is used in libs to handle arch-dependent submanifests, like
// mos_esp8266.yml.
if pc.adjustments.Platform == "" {
pc.adjustments.Platform = manifest.Platform
}
pc.mtx.Unlock()
libManifest, libMtime, err := readManifestWithLibs2(name, libLocalDir, pc)
if err != nil {
lpres <- libPrepareResult{
err: errors.Trace(err),
}
return
}
// Add a build var and C macro MGOS_HAVE_<lib_name>
haveName := fmt.Sprintf(
"MGOS_HAVE_%s", strings.ToUpper(ourutil.IdentifierFromString(name)),
)
pc.mtx.Lock()
manifest.BuildVars[haveName] = "1"
manifest.CDefs[haveName] = "1"
lh := &build.FWAppManifestLibHandled{
Lib: *m,
Path: libLocalDir,
Deps: pc.deps.GetDeps(name),
Manifest: libManifest,
}
lh.Lib.Name = name
pc.libsHandled[name] = lh
pc.initDeps.AddNodeWithDeps(name, libManifest.InitAfter)
if !libManifest.NoImplInitDeps && name != coreLibName {
// Implicit dep on "core"
pc.initDeps.AddDep(name, coreLibName)
}
for _, dep := range libManifest.InitBefore {
pc.initDeps.AddNodeWithDeps(dep, []string{name})
}
pc.mtx.Unlock()
lpres <- libPrepareResult{
mtime: libMtime,
}
}
// ReadManifest reads manifest file(s) from the specific directory; if the
// manifest or given BuildParams have arch specified, then the returned
// manifest will contain all arch-specific adjustments (if any)
func ReadManifest(
appDir string, adjustments *ManifestAdjustments, interp *interpreter.MosInterpreter,
) (*build.FWAppManifest, time.Time, error) {
interp = interp.Copy()
if adjustments == nil {
adjustments = &ManifestAdjustments{}
}
manifestFullName := moscommon.GetManifestFilePath(appDir)
manifest, mtime, err := ReadManifestFile(manifestFullName, interp, true)
if err != nil {
return nil, time.Time{}, errors.Trace(err)
}
// Override arch with the value given in command line
if adjustments.Platform != "" {
manifest.Platform = adjustments.Platform
}
manifest.Platform = strings.ToLower(manifest.Platform)
// Set the mos.platform variable
interp.MVars.SetVar(interpreter.GetMVarNameMosPlatform(), manifest.Platform)
// If type is omitted, assume "app"
if manifest.Type == "" {
manifest.Type = build.AppTypeApp
}
if manifest.Platform != "" {
manifestArchFullName := moscommon.GetManifestArchFilePath(appDir, manifest.Platform)
_, err := os.Stat(manifestArchFullName)
if err == nil {
// Arch-specific mos.yml does exist, so, handle it
archManifest, archMtime, err := ReadManifestFile(manifestArchFullName, interp, false)
if err != nil {
return nil, time.Time{}, errors.Trace(err)
}
// We should return the latest modification date of all encountered
// manifests, so let's see if we got the later mtime here
if archMtime.After(mtime) {
mtime = archMtime
}
// Extend common app manifest with arch-specific things.
if err := extendManifest(manifest, manifest, archManifest, "", "", interp, &extendManifestOptions{
skipFailedExpansions: true,
extendInitDeps: true,
}); err != nil {
return nil, time.Time{}, errors.Trace(err)
}
} else if !os.IsNotExist(err) {
// Some error other than non-existing mos_<arch>.yml; complain.
return nil, time.Time{}, errors.Trace(err)
}
}
if manifest.Platforms == nil {
manifest.Platforms = []string{}
}
// Apply adjustments (other than Platform which was applied earlier)
if err := extendManifest(
manifest, manifest, &build.FWAppManifest{
BuildVars: adjustments.BuildVars,
}, "", "", interp, &extendManifestOptions{
skipFailedExpansions: true,
},
); err != nil {
return nil, time.Time{}, errors.Trace(err)
}
return manifest, mtime, nil
}
func checkWarningAndError(manifest *build.FWAppManifest) error {
if manifest.Error != "" {
ourutil.Reportf("Error: %s: %s", manifest.Origin, manifest.Error)
return errors.Errorf("%s: %s", manifest.Origin, manifest.Error)
}
if manifest.Warning != "" {
ourutil.Reportf("Warning: %s: %s", manifest.Origin, manifest.Warning)
}
return nil
}
// ReadManifestFile reads single manifest file (which can be either "main" app
// or lib manifest, or some arch-specific adjustment manifest)
func ReadManifestFile(
manifestFullName string, interp *interpreter.MosInterpreter, manifestVersionMandatory bool,
) (*build.FWAppManifest, time.Time, error) {
interp = interp.Copy()
var manifestSrc []byte
var err error
if !strings.HasPrefix(manifestFullName, assetPrefix) {
// Reading regular file from the host filesystem
manifestSrc, err = ioutil.ReadFile(manifestFullName)
} else {
// Reading the asset
assetName := manifestFullName[len(assetPrefix):]
manifestSrc, err = Asset(assetName)
}
if err != nil {
return nil, time.Time{}, errors.Annotatef(err, "reading manifest %q", manifestFullName)
}
var manifest build.FWAppManifest
if err := yaml.Unmarshal(manifestSrc, &manifest); err != nil {
return nil, time.Time{}, errors.Annotatef(err, "parsing manifest %q", manifestFullName)
}
manifest.Origin = manifestFullName
if manifest.ManifestVersion != "" {
// Check if manifest manifest version is supported by the mos tool
if manifest.ManifestVersion < minManifestVersion {
return nil, time.Time{}, errors.Errorf(
"too old manifest_version %q in %q (oldest supported is %q)",
manifest.ManifestVersion, manifestFullName, minManifestVersion,
)
}
if manifest.ManifestVersion > maxManifestVersion {
return nil, time.Time{}, errors.Errorf(
"too new manifest_version %q in %q (latest supported is %q). Please run \"mos update\".",
manifest.ManifestVersion, manifestFullName, maxManifestVersion,
)
}
} else if manifestVersionMandatory {
return nil, time.Time{}, errors.Errorf(
"manifest version is missing in %q", manifestFullName,
)
}
if err = checkWarningAndError(&manifest); err != nil {
return nil, time.Time{}, errors.Trace(err)
}
for i, _ := range manifest.Modules {
if err = manifest.Modules[i].Normalize(); err != nil {
return nil, time.Time{}, errors.Trace(err)
}
}
if manifest.BuildVars == nil {
manifest.BuildVars = make(map[string]string)
}
if manifest.CDefs == nil {
manifest.CDefs = make(map[string]string)
}
if manifest.MongooseOsVersion == "" {
manifest.MongooseOsVersion = interpreter.WrapMosExpr(interpreter.GetMVarNameMosVersion())
}
if manifest.LibsVersion == "" {