forked from google/blueprint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
2584 lines (2160 loc) · 66.9 KB
/
context.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 2014 Google Inc. 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.
package blueprint
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"runtime"
"sort"
"strconv"
"strings"
"text/scanner"
"text/template"
"github.com/google/blueprint/parser"
"github.com/google/blueprint/pathtools"
"github.com/google/blueprint/proptools"
)
var ErrBuildActionsNotReady = errors.New("build actions are not ready")
const maxErrors = 10
// A Context contains all the state needed to parse a set of Blueprints files
// and generate a Ninja file. The process of generating a Ninja file proceeds
// through a series of four phases. Each phase corresponds with a some methods
// on the Context object
//
// Phase Methods
// ------------ -------------------------------------------
// 1. Registration RegisterModuleType, RegisterSingletonType
//
// 2. Parse ParseBlueprintsFiles, Parse
//
// 3. Generate ResolveDependencies, PrepareBuildActions
//
// 4. Write WriteBuildFile
//
// The registration phase prepares the context to process Blueprints files
// containing various types of modules. The parse phase reads in one or more
// Blueprints files and validates their contents against the module types that
// have been registered. The generate phase then analyzes the parsed Blueprints
// contents to create an internal representation for the build actions that must
// be performed. This phase also performs validation of the module dependencies
// and property values defined in the parsed Blueprints files. Finally, the
// write phase generates the Ninja manifest text based on the generated build
// actions.
type Context struct {
// set at instantiation
moduleFactories map[string]ModuleFactory
moduleGroups map[string]*moduleGroup
moduleInfo map[Module]*moduleInfo
modulesSorted []*moduleInfo
singletonInfo map[string]*singletonInfo
mutatorInfo []*mutatorInfo
earlyMutatorInfo []*earlyMutatorInfo
variantMutatorNames []string
moduleNinjaNames map[string]*moduleGroup
dependenciesReady bool // set to true on a successful ResolveDependencies
buildActionsReady bool // set to true on a successful PrepareBuildActions
// set by SetIgnoreUnknownModuleTypes
ignoreUnknownModuleTypes bool
// set during PrepareBuildActions
pkgNames map[*PackageContext]string
globalVariables map[Variable]*ninjaString
globalPools map[Pool]*poolDef
globalRules map[Rule]*ruleDef
// set during PrepareBuildActions
buildDir *ninjaString // The builddir special Ninja variable
requiredNinjaMajor int // For the ninja_required_version variable
requiredNinjaMinor int // For the ninja_required_version variable
requiredNinjaMicro int // For the ninja_required_version variable
// set lazily by sortedModuleNames
cachedSortedModuleNames []string
}
// An Error describes a problem that was encountered that is related to a
// particular location in a Blueprints file.
type Error struct {
Err error // the error that occurred
Pos scanner.Position // the relevant Blueprints file location
}
type localBuildActions struct {
variables []*localVariable
rules []*localRule
buildDefs []*buildDef
}
type moduleGroup struct {
name string
ninjaName string
modules []*moduleInfo
}
type moduleInfo struct {
// set during Parse
typeName string
relBlueprintsFile string
pos scanner.Position
propertyPos map[string]scanner.Position
properties struct {
Name string
Deps []string
}
variantName string
variant variationMap
dependencyVariant variationMap
logicModule Module
group *moduleGroup
moduleProperties []interface{}
// set during ResolveDependencies
directDeps []*moduleInfo
// set during updateDependencies
reverseDeps []*moduleInfo
depsCount int
// used by parallelVisitAllBottomUp
waitingCount int
// set during each runMutator
splitModules []*moduleInfo
// set during PrepareBuildActions
actionDefs localBuildActions
}
// A Variation is a way that a variant of a module differs from other variants of the same module.
// For example, two variants of the same module might have Variation{"arch","arm"} and
// Variation{"arch","arm64"}
type Variation struct {
// Mutator is the axis on which this variation applies, i.e. "arch" or "link"
Mutator string
// Variation is the name of the variation on the axis, i.e. "arm" or "arm64" for arch, or
// "shared" or "static" for link.
Variation string
}
// A variationMap stores a map of Mutator to Variation to specify a variant of a module.
type variationMap map[string]string
func (vm variationMap) clone() variationMap {
newVm := make(variationMap)
for k, v := range vm {
newVm[k] = v
}
return newVm
}
// Compare this variationMap to another one. Returns true if the every entry in this map
// is either the same in the other map or doesn't exist in the other map.
func (vm variationMap) subset(other variationMap) bool {
for k, v1 := range vm {
if v2, ok := other[k]; ok && v1 != v2 {
return false
}
}
return true
}
func (vm variationMap) equal(other variationMap) bool {
return reflect.DeepEqual(vm, other)
}
type singletonInfo struct {
// set during RegisterSingletonType
factory SingletonFactory
singleton Singleton
// set during PrepareBuildActions
actionDefs localBuildActions
}
type mutatorInfo struct {
// set during RegisterMutator
topDownMutator TopDownMutator
bottomUpMutator BottomUpMutator
name string
}
type earlyMutatorInfo struct {
// set during RegisterEarlyMutator
mutator EarlyMutator
name string
}
func (e *Error) Error() string {
return fmt.Sprintf("%s: %s", e.Pos, e.Err)
}
// NewContext creates a new Context object. The created context initially has
// no module or singleton factories registered, so the RegisterModuleFactory and
// RegisterSingletonFactory methods must be called before it can do anything
// useful.
func NewContext() *Context {
return &Context{
moduleFactories: make(map[string]ModuleFactory),
moduleGroups: make(map[string]*moduleGroup),
moduleInfo: make(map[Module]*moduleInfo),
singletonInfo: make(map[string]*singletonInfo),
moduleNinjaNames: make(map[string]*moduleGroup),
}
}
// A ModuleFactory function creates a new Module object. See the
// Context.RegisterModuleType method for details about how a registered
// ModuleFactory is used by a Context.
type ModuleFactory func() (m Module, propertyStructs []interface{})
// RegisterModuleType associates a module type name (which can appear in a
// Blueprints file) with a Module factory function. When the given module type
// name is encountered in a Blueprints file during parsing, the Module factory
// is invoked to instantiate a new Module object to handle the build action
// generation for the module. If a Mutator splits a module into multiple variants,
// the factory is invoked again to create a new Module for each variant.
//
// The module type names given here must be unique for the context. The factory
// function should be a named function so that its package and name can be
// included in the generated Ninja file for debugging purposes.
//
// The factory function returns two values. The first is the newly created
// Module object. The second is a slice of pointers to that Module object's
// properties structs. Each properties struct is examined when parsing a module
// definition of this type in a Blueprints file. Exported fields of the
// properties structs are automatically set to the property values specified in
// the Blueprints file. The properties struct field names determine the name of
// the Blueprints file properties that are used - the Blueprints property name
// matches that of the properties struct field name with the first letter
// converted to lower-case.
//
// The fields of the properties struct must be either []string, a string, or
// bool. The Context will panic if a Module gets instantiated with a properties
// struct containing a field that is not one these supported types.
//
// Any properties that appear in the Blueprints files that are not built-in
// module properties (such as "name" and "deps") and do not have a corresponding
// field in the returned module properties struct result in an error during the
// Context's parse phase.
//
// As an example, the follow code:
//
// type myModule struct {
// properties struct {
// Foo string
// Bar []string
// }
// }
//
// func NewMyModule() (blueprint.Module, []interface{}) {
// module := new(myModule)
// properties := &module.properties
// return module, []interface{}{properties}
// }
//
// func main() {
// ctx := blueprint.NewContext()
// ctx.RegisterModuleType("my_module", NewMyModule)
// // ...
// }
//
// would support parsing a module defined in a Blueprints file as follows:
//
// my_module {
// name: "myName",
// foo: "my foo string",
// bar: ["my", "bar", "strings"],
// }
//
// The factory function may be called from multiple goroutines. Any accesses
// to global variables must be synchronized.
func (c *Context) RegisterModuleType(name string, factory ModuleFactory) {
if _, present := c.moduleFactories[name]; present {
panic(errors.New("module type name is already registered"))
}
c.moduleFactories[name] = factory
}
// A SingletonFactory function creates a new Singleton object. See the
// Context.RegisterSingletonType method for details about how a registered
// SingletonFactory is used by a Context.
type SingletonFactory func() Singleton
// RegisterSingletonType registers a singleton type that will be invoked to
// generate build actions. Each registered singleton type is instantiated and
// and invoked exactly once as part of the generate phase.
//
// The singleton type names given here must be unique for the context. The
// factory function should be a named function so that its package and name can
// be included in the generated Ninja file for debugging purposes.
func (c *Context) RegisterSingletonType(name string, factory SingletonFactory) {
if _, present := c.singletonInfo[name]; present {
panic(errors.New("singleton name is already registered"))
}
c.singletonInfo[name] = &singletonInfo{
factory: factory,
singleton: factory(),
}
}
func singletonPkgPath(singleton Singleton) string {
typ := reflect.TypeOf(singleton)
for typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
return typ.PkgPath()
}
func singletonTypeName(singleton Singleton) string {
typ := reflect.TypeOf(singleton)
for typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
return typ.PkgPath() + "." + typ.Name()
}
// RegisterTopDownMutator registers a mutator that will be invoked to propagate
// dependency info top-down between Modules. Each registered mutator
// is invoked in registration order (mixing TopDownMutators and BottomUpMutators)
// once per Module, and is invoked on a module before being invoked on any of its
// dependencies.
//
// The mutator type names given here must be unique to all top down mutators in
// the Context.
func (c *Context) RegisterTopDownMutator(name string, mutator TopDownMutator) {
for _, m := range c.mutatorInfo {
if m.name == name && m.topDownMutator != nil {
panic(fmt.Errorf("mutator name %s is already registered", name))
}
}
c.mutatorInfo = append(c.mutatorInfo, &mutatorInfo{
topDownMutator: mutator,
name: name,
})
}
// RegisterBottomUpMutator registers a mutator that will be invoked to split
// Modules into variants. Each registered mutator is invoked in registration
// order (mixing TopDownMutators and BottomUpMutators) once per Module, and is
// invoked on dependencies before being invoked on dependers.
//
// The mutator type names given here must be unique to all bottom up or early
// mutators in the Context.
func (c *Context) RegisterBottomUpMutator(name string, mutator BottomUpMutator) {
for _, m := range c.variantMutatorNames {
if m == name {
panic(fmt.Errorf("mutator name %s is already registered", name))
}
}
c.mutatorInfo = append(c.mutatorInfo, &mutatorInfo{
bottomUpMutator: mutator,
name: name,
})
c.variantMutatorNames = append(c.variantMutatorNames, name)
}
// RegisterEarlyMutator registers a mutator that will be invoked to split
// Modules into multiple variant Modules before any dependencies have been
// created. Each registered mutator is invoked in registration order once
// per Module (including each variant from previous early mutators). Module
// order is unpredictable.
//
// In order for dependencies to be satisifed in a later pass, all dependencies
// of a module either must have an identical variant or must have no variations.
//
// The mutator type names given here must be unique to all bottom up or early
// mutators in the Context.
func (c *Context) RegisterEarlyMutator(name string, mutator EarlyMutator) {
for _, m := range c.variantMutatorNames {
if m == name {
panic(fmt.Errorf("mutator name %s is already registered", name))
}
}
c.earlyMutatorInfo = append(c.earlyMutatorInfo, &earlyMutatorInfo{
mutator: mutator,
name: name,
})
c.variantMutatorNames = append(c.variantMutatorNames, name)
}
// SetIgnoreUnknownModuleTypes sets the behavior of the context in the case
// where it encounters an unknown module type while parsing Blueprints files. By
// default, the context will report unknown module types as an error. If this
// method is called with ignoreUnknownModuleTypes set to true then the context
// will silently ignore unknown module types.
//
// This method should generally not be used. It exists to facilitate the
// bootstrapping process.
func (c *Context) SetIgnoreUnknownModuleTypes(ignoreUnknownModuleTypes bool) {
c.ignoreUnknownModuleTypes = ignoreUnknownModuleTypes
}
// Parse parses a single Blueprints file from r, creating Module objects for
// each of the module definitions encountered. If the Blueprints file contains
// an assignment to the "subdirs" variable, then the subdirectories listed are
// searched for Blueprints files returned in the subBlueprints return value.
// If the Blueprints file contains an assignment to the "build" variable, then
// the file listed are returned in the subBlueprints return value.
//
// rootDir specifies the path to the root directory of the source tree, while
// filename specifies the path to the Blueprints file. These paths are used for
// error reporting and for determining the module's directory.
func (c *Context) parse(rootDir, filename string, r io.Reader,
scope *parser.Scope) (modules []*moduleInfo, subBlueprints []stringAndScope, deps []string,
errs []error) {
relBlueprintsFile, err := filepath.Rel(rootDir, filename)
if err != nil {
return nil, nil, nil, []error{err}
}
scope = parser.NewScope(scope)
scope.Remove("subdirs")
scope.Remove("build")
file, errs := parser.ParseAndEval(filename, r, scope)
if len(errs) > 0 {
for i, err := range errs {
if parseErr, ok := err.(*parser.ParseError); ok {
err = &Error{
Err: parseErr.Err,
Pos: parseErr.Pos,
}
errs[i] = err
}
}
// If there were any parse errors don't bother trying to interpret the
// result.
return nil, nil, nil, errs
}
for _, def := range file.Defs {
var newErrs []error
var newModule *moduleInfo
switch def := def.(type) {
case *parser.Module:
newModule, newErrs = c.processModuleDef(def, relBlueprintsFile)
case *parser.Assignment:
// Already handled via Scope object
default:
panic("unknown definition type")
}
if len(newErrs) > 0 {
errs = append(errs, newErrs...)
if len(errs) > maxErrors {
break
}
} else if newModule != nil {
modules = append(modules, newModule)
}
}
subdirs, subdirsPos, err := getStringListFromScope(scope, "subdirs")
if err != nil {
errs = append(errs, err)
}
build, buildPos, err := getStringListFromScope(scope, "build")
if err != nil {
errs = append(errs, err)
}
subBlueprintsName, _, err := getStringFromScope(scope, "subname")
blueprints, deps, newErrs := c.findSubdirBlueprints(filepath.Dir(filename), subdirs, build,
subBlueprintsName, subdirsPos, buildPos)
if len(newErrs) > 0 {
errs = append(errs, newErrs...)
}
subBlueprintsAndScope := make([]stringAndScope, len(blueprints))
for i, b := range blueprints {
subBlueprintsAndScope[i] = stringAndScope{b, scope}
}
return modules, subBlueprintsAndScope, deps, errs
}
type stringAndScope struct {
string
*parser.Scope
}
// ParseBlueprintsFiles parses a set of Blueprints files starting with the file
// at rootFile. When it encounters a Blueprints file with a set of subdirs
// listed it recursively parses any Blueprints files found in those
// subdirectories.
//
// If no errors are encountered while parsing the files, the list of paths on
// which the future output will depend is returned. This list will include both
// Blueprints file paths as well as directory paths for cases where wildcard
// subdirs are found.
func (c *Context) ParseBlueprintsFiles(rootFile string) (deps []string,
errs []error) {
c.dependenciesReady = false
rootDir := filepath.Dir(rootFile)
blueprintsSet := make(map[string]bool)
// Channels to receive data back from parseBlueprintsFile goroutines
blueprintsCh := make(chan stringAndScope)
errsCh := make(chan []error)
modulesCh := make(chan []*moduleInfo)
depsCh := make(chan string)
// Channel to notify main loop that a parseBlueprintsFile goroutine has finished
doneCh := make(chan struct{})
// Number of outstanding goroutines to wait for
count := 0
startParseBlueprintsFile := func(filename string, scope *parser.Scope) {
count++
go func() {
c.parseBlueprintsFile(filename, scope, rootDir,
errsCh, modulesCh, blueprintsCh, depsCh)
doneCh <- struct{}{}
}()
}
tooManyErrors := false
startParseBlueprintsFile(rootFile, nil)
loop:
for {
if len(errs) > maxErrors {
tooManyErrors = true
}
select {
case newErrs := <-errsCh:
errs = append(errs, newErrs...)
case dep := <-depsCh:
deps = append(deps, dep)
case modules := <-modulesCh:
newErrs := c.addModules(modules)
errs = append(errs, newErrs...)
case blueprint := <-blueprintsCh:
if tooManyErrors {
continue
}
if blueprintsSet[blueprint.string] {
continue
}
blueprintsSet[blueprint.string] = true
startParseBlueprintsFile(blueprint.string, blueprint.Scope)
case <-doneCh:
count--
if count == 0 {
break loop
}
}
}
return
}
// parseBlueprintFile parses a single Blueprints file, returning any errors through
// errsCh, any defined modules through modulesCh, any sub-Blueprints files through
// blueprintsCh, and any dependencies on Blueprints files or directories through
// depsCh.
func (c *Context) parseBlueprintsFile(filename string, scope *parser.Scope, rootDir string,
errsCh chan<- []error, modulesCh chan<- []*moduleInfo, blueprintsCh chan<- stringAndScope,
depsCh chan<- string) {
file, err := os.Open(filename)
if err != nil {
errsCh <- []error{err}
return
}
modules, subBlueprints, deps, errs := c.parse(rootDir, filename, file, scope)
if len(errs) > 0 {
errsCh <- errs
}
for _, b := range subBlueprints {
blueprintsCh <- b
}
for _, d := range deps {
depsCh <- d
}
err = file.Close()
if err != nil {
errsCh <- []error{err}
}
modulesCh <- modules
}
func (c *Context) findSubdirBlueprints(dir string, subdirs, build []string, subBlueprintsName string,
subdirsPos, buildPos scanner.Position) (blueprints, deps []string, errs []error) {
for _, subdir := range subdirs {
globPattern := filepath.Join(dir, subdir)
matches, matchedDirs, err := pathtools.Glob(globPattern)
if err != nil {
errs = append(errs, &Error{
Err: fmt.Errorf("%q: %s", globPattern, err.Error()),
Pos: subdirsPos,
})
continue
}
if len(matches) == 0 {
errs = append(errs, &Error{
Err: fmt.Errorf("%q: not found", globPattern),
Pos: subdirsPos,
})
}
// Depend on all searched directories so we pick up future changes.
deps = append(deps, matchedDirs...)
for _, foundSubdir := range matches {
fileInfo, subdirStatErr := os.Stat(foundSubdir)
if subdirStatErr != nil {
errs = append(errs, subdirStatErr)
continue
}
// Skip files
if !fileInfo.IsDir() {
continue
}
var subBlueprints string
if subBlueprintsName != "" {
subBlueprints = filepath.Join(foundSubdir, subBlueprintsName)
_, err = os.Stat(subBlueprints)
}
if os.IsNotExist(err) || subBlueprints == "" {
subBlueprints = filepath.Join(foundSubdir, "Blueprints")
_, err = os.Stat(subBlueprints)
}
if os.IsNotExist(err) {
// There is no Blueprints file in this subdirectory. We
// need to add the directory to the list of dependencies
// so that if someone adds a Blueprints file in the
// future we'll pick it up.
deps = append(deps, filepath.Dir(foundSubdir))
} else {
deps = append(deps, subBlueprints)
blueprints = append(blueprints, subBlueprints)
}
}
}
for _, file := range build {
globPattern := filepath.Join(dir, file)
matches, matchedDirs, err := pathtools.Glob(globPattern)
if err != nil {
errs = append(errs, &Error{
Err: fmt.Errorf("%q: %s", globPattern, err.Error()),
Pos: buildPos,
})
continue
}
if len(matches) == 0 {
errs = append(errs, &Error{
Err: fmt.Errorf("%q: not found", globPattern),
Pos: buildPos,
})
}
// Depend on all searched directories so we pick up future changes.
deps = append(deps, matchedDirs...)
for _, foundBlueprints := range matches {
fileInfo, err := os.Stat(foundBlueprints)
if os.IsNotExist(err) {
errs = append(errs, &Error{
Err: fmt.Errorf("%q not found", foundBlueprints),
})
continue
}
if fileInfo.IsDir() {
errs = append(errs, &Error{
Err: fmt.Errorf("%q is a directory", foundBlueprints),
})
continue
}
blueprints = append(blueprints, foundBlueprints)
}
}
return blueprints, deps, errs
}
func getStringListFromScope(scope *parser.Scope, v string) ([]string, scanner.Position, error) {
if assignment, err := scope.Get(v); err == nil {
switch assignment.Value.Type {
case parser.List:
ret := make([]string, 0, len(assignment.Value.ListValue))
for _, value := range assignment.Value.ListValue {
if value.Type != parser.String {
// The parser should not produce this.
panic("non-string value found in list")
}
ret = append(ret, value.StringValue)
}
return ret, assignment.Pos, nil
case parser.Bool, parser.String:
return nil, scanner.Position{}, &Error{
Err: fmt.Errorf("%q must be a list of strings", v),
Pos: assignment.Pos,
}
default:
panic(fmt.Errorf("unknown value type: %d", assignment.Value.Type))
}
}
return nil, scanner.Position{}, nil
}
func getStringFromScope(scope *parser.Scope, v string) (string, scanner.Position, error) {
if assignment, err := scope.Get(v); err == nil {
switch assignment.Value.Type {
case parser.String:
return assignment.Value.StringValue, assignment.Pos, nil
case parser.Bool, parser.List:
return "", scanner.Position{}, &Error{
Err: fmt.Errorf("%q must be a string", v),
Pos: assignment.Pos,
}
default:
panic(fmt.Errorf("unknown value type: %d", assignment.Value.Type))
}
}
return "", scanner.Position{}, nil
}
func (c *Context) createVariations(origModule *moduleInfo, mutatorName string,
variationNames []string) ([]*moduleInfo, []error) {
if len(variationNames) == 0 {
panic(fmt.Errorf("mutator %q passed zero-length variation list for module %q",
mutatorName, origModule.properties.Name))
}
newModules := []*moduleInfo{}
var errs []error
for i, variationName := range variationNames {
typeName := origModule.typeName
factory, ok := c.moduleFactories[typeName]
if !ok {
panic(fmt.Sprintf("unrecognized module type %q during cloning", typeName))
}
var newLogicModule Module
var newProperties []interface{}
if i == 0 {
// Reuse the existing module for the first new variant
// This both saves creating a new module, and causes the insertion in c.moduleInfo below
// with logicModule as the key to replace the original entry in c.moduleInfo
newLogicModule = origModule.logicModule
newProperties = origModule.moduleProperties
} else {
props := []interface{}{
&origModule.properties,
}
newLogicModule, newProperties = factory()
newProperties = append(props, newProperties...)
if len(newProperties) != len(origModule.moduleProperties) {
panic("mismatched properties array length in " + origModule.properties.Name)
}
for i := range newProperties {
dst := reflect.ValueOf(newProperties[i]).Elem()
src := reflect.ValueOf(origModule.moduleProperties[i]).Elem()
proptools.CopyProperties(dst, src)
}
}
newVariant := origModule.variant.clone()
newVariant[mutatorName] = variationName
m := *origModule
newModule := &m
newModule.directDeps = append([]*moduleInfo(nil), origModule.directDeps...)
newModule.logicModule = newLogicModule
newModule.variant = newVariant
newModule.dependencyVariant = origModule.dependencyVariant.clone()
newModule.moduleProperties = newProperties
if newModule.variantName == "" {
newModule.variantName = variationName
} else {
newModule.variantName += "_" + variationName
}
newModules = append(newModules, newModule)
// Insert the new variant into the global module map. If this is the first variant then
// it reuses logicModule from the original module, which causes this to replace the
// original module in the global module map.
c.moduleInfo[newModule.logicModule] = newModule
newErrs := c.convertDepsToVariation(newModule, mutatorName, variationName)
if len(newErrs) > 0 {
errs = append(errs, newErrs...)
}
}
// Mark original variant as invalid. Modules that depend on this module will still
// depend on origModule, but we'll fix it when the mutator is called on them.
origModule.logicModule = nil
origModule.splitModules = newModules
return newModules, errs
}
func (c *Context) convertDepsToVariation(module *moduleInfo,
mutatorName, variationName string) (errs []error) {
for i, dep := range module.directDeps {
if dep.logicModule == nil {
var newDep *moduleInfo
for _, m := range dep.splitModules {
if m.variant[mutatorName] == variationName {
newDep = m
break
}
}
if newDep == nil {
errs = append(errs, &Error{
Err: fmt.Errorf("failed to find variation %q for module %q needed by %q",
variationName, dep.properties.Name, module.properties.Name),
Pos: module.pos,
})
continue
}
module.directDeps[i] = newDep
}
}
return errs
}
func (c *Context) prettyPrintVariant(variant variationMap) string {
names := make([]string, 0, len(variant))
for _, m := range c.variantMutatorNames {
if v, ok := variant[m]; ok {
names = append(names, m+":"+v)
}
}
return strings.Join(names, ", ")
}
func (c *Context) processModuleDef(moduleDef *parser.Module,
relBlueprintsFile string) (*moduleInfo, []error) {
typeName := moduleDef.Type.Name
factory, ok := c.moduleFactories[typeName]
if !ok {
if c.ignoreUnknownModuleTypes {
return nil, nil
}
return nil, []error{
&Error{
Err: fmt.Errorf("unrecognized module type %q", typeName),
Pos: moduleDef.Type.Pos,
},
}
}
logicModule, properties := factory()
module := &moduleInfo{
logicModule: logicModule,
typeName: typeName,
relBlueprintsFile: relBlueprintsFile,
}
props := []interface{}{
&module.properties,
}
properties = append(props, properties...)
module.moduleProperties = properties
propertyMap, errs := unpackProperties(moduleDef.Properties, properties...)
if len(errs) > 0 {
return nil, errs
}
module.pos = moduleDef.Type.Pos
module.propertyPos = make(map[string]scanner.Position)
for name, propertyDef := range propertyMap {
module.propertyPos[name] = propertyDef.Pos
}
return module, nil
}
func (c *Context) addModules(modules []*moduleInfo) (errs []error) {
for _, module := range modules {
name := module.properties.Name
c.moduleInfo[module.logicModule] = module
if group, present := c.moduleGroups[name]; present {
errs = append(errs, []error{
&Error{
Err: fmt.Errorf("module %q already defined", name),
Pos: module.pos,
},
&Error{
Err: fmt.Errorf("<-- previous definition here"),
Pos: group.modules[0].pos,
},
}...)
continue
} else {
ninjaName := toNinjaName(module.properties.Name)
// The sanitizing in toNinjaName can result in collisions, uniquify the name if it
// already exists
for i := 0; c.moduleNinjaNames[ninjaName] != nil; i++ {
ninjaName = toNinjaName(module.properties.Name) + strconv.Itoa(i)
}
group := &moduleGroup{
name: module.properties.Name,
ninjaName: ninjaName,
modules: []*moduleInfo{module},
}
module.group = group
c.moduleGroups[name] = group
c.moduleNinjaNames[ninjaName] = group
}
}
return errs
}
// ResolveDependencies checks that the dependencies specified by all of the
// modules defined in the parsed Blueprints files are valid. This means that
// the modules depended upon are defined and that no circular dependencies
// exist.
//
// The config argument is made available to all of the DynamicDependerModule
// objects via the Config method on the DynamicDependerModuleContext objects