-
Notifications
You must be signed in to change notification settings - Fork 219
Expand file tree
/
Copy pathbuiltins.go
More file actions
1625 lines (1460 loc) · 49.6 KB
/
Copy pathbuiltins.go
File metadata and controls
1625 lines (1460 loc) · 49.6 KB
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
package asp
import (
"encoding/json"
"errors"
"fmt"
"io"
"path/filepath"
"reflect"
"slices"
"sort"
"strconv"
"strings"
"sync"
"unicode"
"github.com/Masterminds/semver/v3"
"github.com/manifoldco/promptui"
"github.com/thought-machine/please/src/cli"
"github.com/thought-machine/please/src/core"
"github.com/thought-machine/please/src/fs"
)
// A nativeFunc is a function that implements a builtin function natively.
type nativeFunc func(*scope, []pyObject) pyObject
// registerBuiltins sets up the "special" builtins that map to native code.
func registerBuiltins(s *scope) {
const varargs = true
const kwargs = true
setNativeCode(s, "build_rule", buildRule)
setNativeCode(s, "tag", tag)
setNativeCode(s, "subrepo", subrepo)
setNativeCode(s, "fail", builtinFail)
setNativeCode(s, "subinclude", subinclude, varargs)
setNativeCode(s, "load", bazelLoad, varargs)
setNativeCode(s, "package", pkg, false, kwargs)
setNativeCode(s, "sorted", sorted)
setNativeCode(s, "reversed", reversed)
setNativeCode(s, "filter", filter)
setNativeCode(s, "map", mapFunc)
setNativeCode(s, "reduce", reduce)
setNativeCode(s, "isinstance", isinstance)
setNativeCode(s, "range", pyRangeFunc)
setNativeCode(s, "enumerate", enumerate)
setNativeCode(s, "zip", zip, varargs)
setNativeCode(s, "any", anyFunc)
setNativeCode(s, "all", allFunc)
setNativeCode(s, "min", min)
setNativeCode(s, "max", max)
setNativeCode(s, "chr", chr)
setNativeCode(s, "ord", ord)
setNativeCode(s, "len", lenFunc)
setNativeCode(s, "glob", glob)
setNativeCode(s, "bool", boolType)
setNativeCode(s, "int", intType)
setNativeCode(s, "str", strType)
setNativeCode(s, "join_path", joinPath, varargs)
setNativeCode(s, "get_base_path", packageName)
setNativeCode(s, "package_name", packageName)
setNativeCode(s, "subrepo_name", subrepoName)
setNativeCode(s, "canonicalise", canonicalise)
setNativeCode(s, "get_labels", getLabels)
setNativeCode(s, "add_label", addLabel)
setNativeCode(s, "add_dep", addDep)
setNativeCode(s, "add_data", addData)
setNativeCode(s, "add_out", addOut)
setNativeCode(s, "get_outs", getOuts)
setNativeCode(s, "get_named_outs", getNamedOuts)
setNativeCode(s, "add_entry_point", addEntryPoint)
setNativeCode(s, "get_entry_points", getEntryPoints)
setNativeCode(s, "add_licence", addLicence)
setNativeCode(s, "get_licences", getLicences)
setNativeCode(s, "get_command", getCommand)
setNativeCode(s, "set_command", setCommand)
setNativeCode(s, "json", valueAsJSON)
setNativeCode(s, "breakpoint", breakpoint)
setNativeCode(s, "is_semver", isSemver)
setNativeCode(s, "semver_check", semverCheck)
setNativeCode(s, "looks_like_build_label", looksLikeBuildLabel)
s.interpreter.stringMethods = map[string]*pyFunc{
"join": setNativeCode(s, "join", strJoin),
"split": setNativeCode(s, "split", strSplit),
"replace": setNativeCode(s, "replace", strReplace),
"partition": setNativeCode(s, "partition", strPartition),
"rpartition": setNativeCode(s, "rpartition", strRPartition),
"startswith": setNativeCode(s, "startswith", strStartsWith),
"endswith": setNativeCode(s, "endswith", strEndsWith),
"lstrip": setNativeCode(s, "lstrip", strLStrip),
"rstrip": setNativeCode(s, "rstrip", strRStrip),
"removeprefix": setNativeCode(s, "removeprefix", strRemovePrefix),
"removesuffix": setNativeCode(s, "removesuffix", strRemoveSuffix),
"strip": setNativeCode(s, "strip", strStrip),
"find": setNativeCode(s, "find", strFind),
"rfind": setNativeCode(s, "rfind", strRFind),
"format": setNativeCode(s, "format", strFormat),
"count": setNativeCode(s, "count", strCount),
"upper": setNativeCode(s, "upper", strUpper),
"lower": setNativeCode(s, "lower", strLower),
}
s.interpreter.stringMethods["format"].kwargs = true
s.interpreter.dictMethods = map[string]*pyFunc{
"get": setNativeCode(s, "get", dictGet),
"setdefault": s.Lookup("setdefault").(*pyFunc),
"keys": setNativeCode(s, "keys", dictKeys),
"items": setNativeCode(s, "items", dictItems),
"values": setNativeCode(s, "values", dictValues),
"copy": setNativeCode(s, "copy", dictCopy),
}
s.interpreter.configMethods = map[string]*pyFunc{
"get": setNativeCode(s, "config_get", configGet),
"setdefault": s.Lookup("setdefault").(*pyFunc),
"keys": setNativeCode(s, "config_keys", configKeys),
"items": setNativeCode(s, "config_items", configItems),
"values": setNativeCode(s, "config_values", configValues),
}
if s.state.Config.Parse.GitFunctions {
setNativeCode(s, "git_branch", execGitBranch)
setNativeCode(s, "git_commit", execGitCommit)
setNativeCode(s, "git_show", execGitShow)
setNativeCode(s, "git_state", execGitState)
}
setLogCode(s, "debug", log.Debug)
setLogCode(s, "info", log.Info)
setLogCode(s, "notice", log.Notice)
setLogCode(s, "warning", log.Warning)
setLogCode(s, "error", log.Errorf)
setLogCode(s, "fatal", log.Fatalf)
}
// registerSubincludePackage sets up the package for remote subincludes.
func registerSubincludePackage(s *scope) {
// Another small hack - replace the code for these two with native code, must be done after the
// declarations which are in misc_rules.
buildRule := s.Lookup("build_rule").(*pyFunc)
f := setNativeCode(s, "filegroup", filegroup)
f.args = buildRule.args
f.argIndices = buildRule.argIndices
f.defaults = buildRule.defaults
f.constants = buildRule.constants
f.types = buildRule.types
f.args = buildRule.args
f.argIndices = buildRule.argIndices
f.defaults = buildRule.defaults
f.constants = buildRule.constants
f.types = buildRule.types
}
func setNativeCode(s *scope, name string, code nativeFunc, flags ...bool) *pyFunc {
f := s.Lookup(name).(*pyFunc)
f.nativeCode = code
f.code = nil // Might as well save a little memory here
if len(flags) != 0 {
f.varargs = flags[0]
f.kwargs = len(flags) > 1 && flags[1]
} else {
f.argPool = &sync.Pool{
New: func() interface{} {
return make([]pyObject, len(f.args))
},
}
}
return f
}
// setLogCode specialises setNativeCode for handling the log functions (of which there are a few)
func setLogCode(s *scope, name string, f func(format string, args ...interface{})) {
setNativeCode(s, name, func(s *scope, args []pyObject) pyObject {
if str, ok := args[0].(pyString); ok {
l := make([]interface{}, len(args))
for i, arg := range args {
l[i] = arg
}
f("%s: %s", s.pkgFilename(), fmt.Sprintf(string(str), l[1:]...))
return None
}
f("%s: %s", s.pkgFilename(), args)
return None
}).varargs = true
}
// buildRule implements the build_rule() builtin function.
// This is the main interface point; every build rule ultimately calls this to add
// new objects to the build graph.
func buildRule(s *scope, args []pyObject) pyObject {
s.NAssert(s.pkg == nil, "Cannot create new build rules in this scope")
// We need to set various defaults from config here; it is useful to put it on the rule but not often so
// because most rules pass them through anyway.
// TODO(peterebden): when we get rid of the old parser, put these defaults on all the build rules and
// get rid of this.
args[visibilityBuildRuleArgIdx] = defaultFromConfig(s.config, args[visibilityBuildRuleArgIdx], "DEFAULT_VISIBILITY")
args[testOnlyBuildRuleArgIdx] = defaultFromConfig(s.config, args[testOnlyBuildRuleArgIdx], "DEFAULT_TESTONLY")
args[licencesBuildRuleArgIdx] = defaultFromConfig(s.config, args[licencesBuildRuleArgIdx], "DEFAULT_LICENCES")
args[sandboxBuildRuleArgIdx] = defaultFromConfig(s.config, args[sandboxBuildRuleArgIdx], "BUILD_SANDBOX")
args[testSandboxBuildRuleArgIdx] = defaultFromConfig(s.config, args[testSandboxBuildRuleArgIdx], "TEST_SANDBOX")
// Don't want to remote execute a target if we need system sources
if args[systemSrcsBuildRuleArgIdx] != None {
args[localBuildRuleArgIdx] = pyString("True")
}
target := createTarget(s, args)
s.Assert(s.pkg.Target(target.Label.Name) == nil, "Duplicate build target in %s: %s", s.pkg.Name, target.Label.Name)
populateTarget(s, target, args)
s.state.AddTarget(s.pkg, target)
if s.Callback {
target.AddedPostBuild = true
}
if s.parsingFor != nil && s.parsingFor.label == target.Label {
if err := s.state.ActivateTarget(s.pkg, s.parsingFor.label, s.parsingFor.dependent, s.mode); err != nil {
s.Error("%v", err)
}
}
if s.state.IsPendingTarget(target.Label) {
if err := s.state.ActivateTarget(s.pkg, target.Label, target.Label, s.mode); err != nil {
s.Error("%v", err)
}
}
return pyString(":" + target.Label.Name)
}
// defaultFromConfig sets a default value from the config if the property isn't set.
func defaultFromConfig(config *pyConfig, arg pyObject, name string) pyObject {
if arg == nil || arg == None {
return config.Get(name, arg)
}
return arg
}
// filegroup implements the filegroup() builtin.
func filegroup(s *scope, args []pyObject) pyObject {
args[1] = filegroupCommand
return buildRule(s, args)
}
// pkg implements the package() builtin function.
func pkg(s *scope, args []pyObject) pyObject {
s.Assert(s.pkg.NumTargets() == 0, "package() must be called before any build targets are defined")
for k, v := range s.locals {
k = strings.ToUpper(k)
configVal := s.config.Get(k, nil)
s.Assert(configVal != nil, "error calling package(): %s is not a known config value", k)
// Merge in the existing config for dictionaries
if overrides, ok := v.(pyDict); ok {
if pluginConfig, ok := configVal.(pyDict); ok {
newPluginConfig := pluginConfig.Copy()
for pluginKey, override := range overrides {
pluginKey = strings.ToUpper(pluginKey)
if _, ok := newPluginConfig[pluginKey]; !ok {
s.Error("error calling package(): %s.%s is not a known config value", k, pluginKey)
}
newPluginConfig.IndexAssign(pyString(pluginKey), override)
}
v = newPluginConfig
} else {
s.Error("error calling package(): can't assign a dict to %s as it's not a dict", k)
}
}
s.config.IndexAssign(pyString(k), v)
}
return None
}
func tag(s *scope, args []pyObject) pyObject {
name := args[0].String()
tag := args[1].String()
return pyString(tagName(name, tag))
}
// tagName applies the given tag to a target name.
func tagName(name, tag string) string {
if name[0] != '_' {
name = "_" + name
}
if strings.ContainsRune(name, '#') {
name += "_"
} else {
name += "#"
}
return name + tag
}
// bazelLoad implements the load() builtin, which is only available for Bazel compatibility.
func bazelLoad(s *scope, args []pyObject) pyObject {
s.Assert(s.state.Config.Bazel.Compatibility, "load() is only available in Bazel compatibility mode. See `plz help bazel` for more information.")
// The argument always looks like a build label, but it is not really one (i.e. there is no BUILD file that defines it).
// We do not support their legacy syntax here (i.e. "/tools/build_rules/build_test" etc).
l := s.parseLabelInContextPkg(string(args[0].(pyString)))
filename := filepath.Join(l.PackageName, l.Name)
if l.Subrepo != "" {
subrepo := s.state.Graph.Subrepo(l.Subrepo)
if subrepo == nil || (subrepo.Target != nil && subrepo != s.contextPackage().Subrepo) {
subincludeTarget(s, l)
subrepo = s.state.Graph.SubrepoOrDie(l.Subrepo)
}
filename = subrepo.Dir(filename)
}
s.SetAll(s.interpreter.Subinclude(s, filename, l, false), false)
return None
}
// WaitForSubincludedTarget drops the interpreter lock and waits for the subincluded target to be built. This is
// important to keep us from deadlocking all available parser threads (easy to happen if they're all waiting on a
// single target which now can't start)
func (s *scope) WaitForSubincludedTarget(l, dependent core.BuildLabel) *core.BuildTarget {
s.interpreter.limiter.Release()
defer s.interpreter.limiter.Acquire()
return s.state.WaitForTargetAndEnsureDownload(l, dependent, s.mode.IsPreload())
}
// builtinFail raises an immediate error that can't be intercepted.
func builtinFail(s *scope, args []pyObject) pyObject {
s.Error("%s", string(args[0].(pyString)))
return None
}
func subinclude(s *scope, args []pyObject) pyObject {
if s.contextPackage() == nil {
s.Error("cannot subinclude from this scope")
}
var si []string
for _, arg := range args {
if l, ok := arg.(pyList); ok {
for _, e := range l {
if l, ok := e.(pyString); ok {
si = append(si, string(l))
} else {
s.Error("cannot subinclude type %s", e.Type())
}
}
} else if l, ok := arg.(pyString); ok {
si = append(si, string(l))
} else {
s.Error("cannot subinclude type %s", arg.Type())
}
}
for _, arg := range si {
label, annotation := core.SplitLabelAnnotation(arg)
t := subincludeTarget(s, s.parseLabelInContextPkg(label))
s.Assert(s.contextPackage().Label().CanSee(s.state, t), "Target %s isn't visible to be subincluded into %s", t.Label, s.contextPackage().Label())
incPkgState := s.state
if t.Label.Subrepo != "" {
subrepo := s.state.Graph.SubrepoOrDie(t.Label.Subrepo)
incPkgState = subrepo.State
}
s.interpreter.loadPluginConfig(s, incPkgState)
var outs []string
if len(annotation) > 0 {
outs = t.NamedOutputs(annotation)
} else {
outs = t.Outputs()
}
for _, out := range outs {
s.SetAll(s.interpreter.Subinclude(s, filepath.Join(t.OutDir(), out), t.Label, false), false)
}
}
return None
}
// subincludeTarget returns the target for a subinclude() call to a label.
// It blocks until the target exists and is built.
func subincludeTarget(s *scope, l core.BuildLabel) *core.BuildTarget {
s.NAssert(l.IsPseudoTarget(), "Can't pass :all or /... to subinclude()")
pkg := s.contextPackage()
pkgLabel := pkg.Label()
// If we're including from a subrepo, or if we're in a subrepo and including from a different subrepo, make sure
// that package is parsed to avoid locking. Locks can occur when the target's package also subincludes that target.
//
// When this happens, both parse thread "WaitForBuiltTarget" expecting the other to queue the target to be built.
//
// By parsing the package first, the subrepo package's subinclude will queue the subrepo target to be built before
// we call WaitForSubincludedTarget below avoiding the lockup.
subrepoLabel := l.SubrepoLabel(s.state)
if l.Subrepo != "" && subrepoLabel.PackageName != pkg.Name && l.Subrepo != pkg.SubrepoName {
subrepoPackageLabel := core.BuildLabel{
PackageName: subrepoLabel.PackageName,
Subrepo: subrepoLabel.Subrepo,
Name: "all",
}
s.state.WaitForPackage(subrepoPackageLabel, pkgLabel, s.mode|core.ParseModeForSubinclude)
}
// isLocal is true when this subinclude target in the current package being parsed
isLocal := s.pkg != nil && l.Subrepo == s.pkg.Label().Subrepo && l.PackageName == s.pkg.Name
// If the subinclude is local to this package, it must already exist in the graph. If it already exists in the graph
// but isn't activated, we should activate it otherwise WaitForSubincludedTarget might block. This can happen when
// another package also subincludes this target, and queues it first.
t := s.state.Graph.Target(l)
if t != nil {
if t.State() < core.Active {
if err := s.state.ActivateTarget(s.pkg, l, pkgLabel, s.mode|core.ParseModeForSubinclude); err != nil {
s.Error("Failed to activate subinclude target: %v", err)
}
}
} else if isLocal {
s.Error("Target :%s is not defined in this package; it has to be defined before the subinclude() call", l.Name)
}
t = s.WaitForSubincludedTarget(l, pkgLabel)
if s.pkg != nil {
s.pkg.RegisterSubinclude(l)
} else if s.subincludeLabel != nil { // If this is nil, that indicates a preloadedSubinclude
s.state.Graph.RegisterTransitiveSubinclude(*s.subincludeLabel, l)
}
return t
}
func lenFunc(s *scope, args []pyObject) pyObject {
return objLen(args[0])
}
func objLen(obj pyObject) pyInt {
if l, ok := obj.(lengthable); ok {
return newPyInt(l.Len())
}
panic("object of type " + obj.Type() + " has no len()")
}
func chr(s *scope, args []pyObject) pyObject {
i, isInt := args[0].(pyInt)
s.Assert(isInt, "Argument i must be an integer, not %s", args[0].Type())
s.Assert(i >= 0 && i <= unicode.MaxRune, "Argument i must be within the Unicode code point range")
return pyString(rune(i))
}
func ord(s *scope, args []pyObject) pyObject {
c, isStr := args[0].(pyString)
s.Assert(isStr, "Argument c must be a string, not %s", args[0].Type())
s.Assert(objLen(c) == 1, "Argument c must be a string containing a single Unicode character")
return newPyInt(int([]rune(c)[0]))
}
func isinstance(s *scope, args []pyObject) pyObject {
obj := args[0]
typesArg := args[1]
var types pyList
if l, ok := typesArg.(pyList); ok {
types = l
} else {
types = pyList{typesArg}
}
for _, li := range types {
// Special case for 'str' and so forth that are functions but also types.
if lif, ok := li.(*pyFunc); ok && isType(obj, lif.name) {
return True
} else if _, ok := obj.(*pyFunc); ok {
continue // reflect would always return true
} else if reflect.TypeOf(obj) == reflect.TypeOf(li) {
return True
}
}
if _, ok := obj.(*pyFunc); ok {
return False // reflect would always return true
}
return newPyBool(reflect.TypeOf(obj) == reflect.TypeOf(typesArg))
}
func isType(obj pyObject, name string) bool {
switch obj.(type) {
case pyBool:
return name == "bool" || name == "int" // N.B. For compatibility with old assert statements
case pyInt:
return name == "int"
case pyString:
return name == "str"
case *pyRange:
return name == "range"
case pyList:
return name == "list"
case pyDict:
return name == "dict"
case *pyConfig:
return name == "config"
case *pyFunc:
return name == "callable"
}
return false
}
func strJoin(s *scope, args []pyObject) pyObject {
self := string(args[0].(pyString))
seq := asStringList(s, args[1], "seq")
return pyString(strings.Join(seq, self))
}
func strSplit(s *scope, args []pyObject) pyObject {
self := args[0].(pyString)
on := args[1].(pyString)
return fromStringList(strings.Split(string(self), string(on)))
}
func strReplace(s *scope, args []pyObject) pyObject {
self := args[0].(pyString)
old := args[1].(pyString)
new := args[2].(pyString)
return pyString(strings.ReplaceAll(string(self), string(old), string(new)))
}
func strPartition(s *scope, args []pyObject) pyObject {
self := args[0].(pyString)
sep := args[1].(pyString)
if idx := strings.Index(string(self), string(sep)); idx != -1 {
return pyList{self[:idx], self[idx : idx+len(sep)], self[idx+len(sep):]}
}
return pyList{self, pyString(""), pyString("")}
}
func strRPartition(s *scope, args []pyObject) pyObject {
self := args[0].(pyString)
sep := args[1].(pyString)
if idx := strings.LastIndex(string(self), string(sep)); idx != -1 {
return pyList{self[:idx], self[idx : idx+len(sep)], self[idx+len(sep):]}
}
return pyList{pyString(""), pyString(""), self}
}
func strStartsWith(s *scope, args []pyObject) pyObject {
self := args[0].(pyString)
x := args[1].(pyString)
return newPyBool(strings.HasPrefix(string(self), string(x)))
}
func strEndsWith(s *scope, args []pyObject) pyObject {
self := args[0].(pyString)
x := args[1].(pyString)
return newPyBool(strings.HasSuffix(string(self), string(x)))
}
func strLStrip(s *scope, args []pyObject) pyObject {
self := args[0].(pyString)
cutset := args[1].(pyString)
return pyString(strings.TrimLeft(string(self), string(cutset)))
}
func strRStrip(s *scope, args []pyObject) pyObject {
self := args[0].(pyString)
cutset := args[1].(pyString)
return pyString(strings.TrimRight(string(self), string(cutset)))
}
func strStrip(s *scope, args []pyObject) pyObject {
self := args[0].(pyString)
cutset := args[1].(pyString)
return pyString(strings.Trim(string(self), string(cutset)))
}
func strRemovePrefix(s *scope, args []pyObject) pyObject {
self := args[0].(pyString)
prefix := args[1].(pyString)
return pyString(strings.TrimPrefix(string(self), string(prefix)))
}
func strRemoveSuffix(s *scope, args []pyObject) pyObject {
self := args[0].(pyString)
suffix := args[1].(pyString)
return pyString(strings.TrimSuffix(string(self), string(suffix)))
}
func strFind(s *scope, args []pyObject) pyObject {
self := args[0].(pyString)
needle := args[1].(pyString)
return newPyInt(strings.Index(string(self), string(needle)))
}
func strRFind(s *scope, args []pyObject) pyObject {
self := args[0].(pyString)
needle := args[1].(pyString)
return newPyInt(strings.LastIndex(string(self), string(needle)))
}
func strFormat(s *scope, args []pyObject) pyObject {
self := string(args[0].(pyString))
var buf strings.Builder
buf.Grow(len(self)) // most reasonable guess available as to how big it might be
arg := 1 // what arg index are we up to for positional args
for {
// Look for either { or }
openIdx := strings.IndexByte(self, '{')
closeIdx := strings.IndexByte(self, '}')
// If neither found, write rest and break
if openIdx == -1 && closeIdx == -1 {
buf.WriteString(self)
break
}
// Check for escaped closing brace }} (when no { or { comes after)
if closeIdx != -1 && (openIdx == -1 || closeIdx < openIdx) {
if closeIdx+1 < len(self) && self[closeIdx+1] == '}' {
buf.WriteString(self[:closeIdx])
buf.WriteByte('}')
self = self[closeIdx+2:]
continue
}
// Unmatched }, just write up to and including it
buf.WriteString(self[:closeIdx+1])
self = self[closeIdx+1:]
continue
}
start := openIdx
// Handle ${{X}} -> ${X} before checking for escaped braces
if start > 0 && self[start-1] == '$' && start+1 < len(self) && self[start+1] == '{' {
end := strings.IndexByte(self[start:], '}')
if end == -1 {
buf.WriteString(self)
break
}
end = start + end
buf.WriteString(self[:start])
buf.WriteString(self[start+1 : end])
self = self[end+1:]
continue
}
// Check for escaped opening brace {{
if start+1 < len(self) && self[start+1] == '{' {
buf.WriteString(self[:start])
buf.WriteByte('{')
self = self[start+2:]
continue
}
end := strings.IndexByte(self[start:], '}')
if end == -1 {
// We may want to error here in some future revision
buf.WriteString(self)
break
}
end = start + end
buf.WriteString(self[:start])
if start > 0 && self[start-1] == '$' {
// Don't interpolate ${X}
if start == end-1 {
// ${} interpolates as $ + positional arg
s.Assert(arg < len(args), "format string specifies at least %d positional arguments, but only %d were supplied", arg, len(args)-1)
buf.WriteString(args[arg].String())
arg++
} else {
buf.WriteString(self[start : end+1])
}
} else if key := self[start+1 : end]; key == "" {
s.Assert(arg < len(args), "format string specifies at least %d positional arguments, but only %d were supplied", arg, len(args)-1)
buf.WriteString(args[arg].String())
arg++
} else if val, present := s.locals[key]; present {
buf.WriteString(val.String())
} else {
// We may want to error here in some future revision
buf.WriteString(self[start : end+1])
}
self = self[end+1:]
}
return pyString(buf.String())
}
func strCount(s *scope, args []pyObject) pyObject {
self := string(args[0].(pyString))
needle := string(args[1].(pyString))
return newPyInt(strings.Count(self, needle))
}
func strUpper(s *scope, args []pyObject) pyObject {
self := string(args[0].(pyString))
return pyString(strings.ToUpper(self))
}
func strLower(s *scope, args []pyObject) pyObject {
self := string(args[0].(pyString))
return pyString(strings.ToLower(self))
}
func boolType(s *scope, args []pyObject) pyObject {
return newPyBool(args[0].IsTruthy())
}
func intType(s *scope, args []pyObject) pyObject {
i, err := strconv.Atoi(string(args[0].(pyString)))
s.Assert(err == nil, "%s", err)
return newPyInt(i)
}
func strType(s *scope, args []pyObject) pyObject {
return pyString(args[0].String())
}
func glob(s *scope, args []pyObject) pyObject {
include := pyStrOrListAsList(s, args[0], "include")
exclude := pyStrOrListAsList(s, args[1], "exclude")
hidden := args[2].IsTruthy()
includeSymlinks := args[3].IsTruthy()
allowEmpty := args[4].IsTruthy()
exclude = append(exclude, s.state.Config.Parse.BuildFileName...)
if s.globber == nil {
if s.pkg.Subrepo != nil {
s.globber = fs.NewGlobber(s.pkg.Subrepo.FS(), s.state.Config.Parse.BuildFileName)
} else {
s.globber = fs.NewGlobber(fs.HostFS, s.state.Config.Parse.BuildFileName)
}
}
glob := s.globber.Glob(s.pkg.Name, include, exclude, hidden, includeSymlinks)
if !allowEmpty && len(glob) == 0 {
// Strip build file name from exclude list for error message
exclude = exclude[:len(exclude)-len(s.state.Config.Parse.BuildFileName)]
log.Fatalf("glob(include=%s, exclude=%s) in %s returned no files. If this is intended, set allow_empty=True on the glob.", include, exclude, s.pkg.Filename)
}
return fromStringList(glob)
}
func pyStrOrListAsList(s *scope, arg pyObject, name string) []string {
if str, ok := arg.(pyString); ok {
return []string{str.String()}
}
return asStringList(s, arg, name)
}
func asStringList(s *scope, arg pyObject, name string) []string {
if fl, ok := arg.(pyFrozenList); ok {
arg = fl.pyList
}
l, ok := arg.(pyList)
s.Assert(ok, "argument %s must be a list", name)
sl := make([]string, len(l))
for i, x := range l {
sx, ok := x.(pyString)
s.Assert(ok, "%s must be a list of strings", name)
sl[i] = string(sx)
}
return sl
}
func fromStringList(l []string) pyList {
ret := make(pyList, len(l))
for i, s := range l {
ret[i] = pyString(s)
}
return ret
}
func configGet(s *scope, args []pyObject) pyObject {
self := args[0].(*pyConfig)
return self.Get(string(args[1].(pyString)), args[2])
}
func configKeys(s *scope, args []pyObject) pyObject {
self := args[0].(*pyConfig)
keys := self.Keys()
ret := make(pyList, len(keys))
for i, k := range keys {
ret[i] = pyString(k)
}
return ret
}
func configValues(s *scope, args []pyObject) pyObject {
self := args[0].(*pyConfig)
keys := self.Keys()
ret := make(pyList, len(keys))
for i, k := range self.Keys() {
// Safe to use MustGet here, since we know the key exists:
ret[i] = self.MustGet(k)
}
return ret
}
func configItems(s *scope, args []pyObject) pyObject {
self := args[0].(*pyConfig)
keys := self.Keys()
ret := make(pyList, len(keys))
for i, k := range self.Keys() {
// Safe to use MustGet here, since we know the key exists:
ret[i] = pyList{pyString(k), self.MustGet(k)}
}
return ret
}
func dictGet(s *scope, args []pyObject) pyObject {
self := args[0].(pyDict)
sk, ok := args[1].(pyString)
s.Assert(ok, "dict keys must be strings, not %s", args[1].Type())
if ret, present := self[string(sk)]; present {
return ret
}
return args[2]
}
func dictKeys(s *scope, args []pyObject) pyObject {
self := args[0].(pyDict)
ret := make(pyList, len(self))
for i, k := range self.Keys() {
ret[i] = pyString(k)
}
return ret
}
func dictValues(s *scope, args []pyObject) pyObject {
self := args[0].(pyDict)
ret := make(pyList, len(self))
for i, k := range self.Keys() {
ret[i] = self[k]
}
return ret
}
func dictItems(s *scope, args []pyObject) pyObject {
self := args[0].(pyDict)
ret := make(pyList, len(self))
for i, k := range self.Keys() {
ret[i] = pyList{pyString(k), self[k]}
}
return ret
}
func dictCopy(s *scope, args []pyObject) pyObject {
self := args[0].(pyDict)
ret := make(pyDict, len(self))
for k, v := range self {
ret[k] = v
}
return ret
}
func sorted(s *scope, args []pyObject) pyObject {
l, isList := args[0].(pyList)
key, isFunc := args[1].(*pyFunc)
reverse, isBool := args[2].(pyBool)
s.Assert(isList, "Argument seq must be a list, not %s", args[0].Type())
s.Assert(isBool, "Argument reverse must be a bool, not %s", args[2].Type())
order := LessThan
if reverse {
order = GreaterThan
}
l = l[:]
if key == nil {
sort.Slice(l, func(i, j int) bool {
return s.operator(order, l[i], l[j]).IsTruthy()
})
} else {
s.Assert(isFunc, "Argument key must be callable, not %s", args[1].Type())
sort.Slice(l, func(i, j int) bool {
iKey := key.Call(s, &Call{
Arguments: []CallArgument{{
Value: Expression{optimised: &optimisedExpression{Constant: l[i]}},
}},
})
jKey := key.Call(s, &Call{
Arguments: []CallArgument{{
Value: Expression{optimised: &optimisedExpression{Constant: l[j]}},
}},
})
return s.operator(order, iKey, jKey).IsTruthy()
})
}
return l
}
func reversed(s *scope, args []pyObject) pyObject {
l, ok := args[0].(pyList)
s.Assert(ok, "irreversible type %s", args[0].Type())
l = l[:]
slices.Reverse(l)
return l
}
func filter(s *scope, args []pyObject) pyObject {
f, isFunc := args[0].(*pyFunc)
l, isList := args[1].(pyList)
s.Assert(isFunc, "Argument filter must be callable, not %s", args[0].Type())
s.Assert(isList, "Argument seq must be a list, not %s", args[1].Type())
var ret pyList
for _, li := range l {
c := &Call{
Arguments: []CallArgument{{
Value: Expression{optimised: &optimisedExpression{Constant: li}},
}},
}
if f.Call(s, c).IsTruthy() {
ret = append(ret, li)
}
}
return ret
}
func mapFunc(s *scope, args []pyObject) pyObject {
mapper, isFunc := args[0].(*pyFunc)
l, isList := args[1].(pyList)
s.Assert(isFunc, "Argument mapper must be callable, not %s", args[0].Type())
s.Assert(isList, "Argument seq must be a list, not %s", args[1].Type())
var ret pyList
for _, li := range l {
c := &Call{
Arguments: []CallArgument{{
Value: Expression{optimised: &optimisedExpression{Constant: li}},
}},
}
ret = append(ret, mapper.Call(s, c))
}
return ret
}
func reduce(s *scope, args []pyObject) pyObject {
reducer, isFunc := args[0].(*pyFunc)
l, isList := args[1].(pyList)
s.Assert(isFunc, "Argument reducer must be callable, not %s", args[0].Type())
s.Assert(isList, "Argument seq must be a list, not %s", args[1].Type())
if len(l) == 0 {
return args[2]
}
var ret pyObject
if ret = args[2]; ret == None {
ret, l = l[0], l[1:]
}
for _, li := range l {
c := &Call{
Arguments: []CallArgument{{
Value: Expression{optimised: &optimisedExpression{Constant: ret}},
}, {
Value: Expression{optimised: &optimisedExpression{Constant: li}},
}},
}
ret = reducer.Call(s, c)
}
return ret
}
func joinPath(s *scope, args []pyObject) pyObject {
l := make([]string, len(args))
for i, arg := range args {
l[i] = string(arg.(pyString))
}
return pyString(filepath.Join(l...))
}
func looksLikeBuildLabel(s *scope, args []pyObject) pyObject {
return pyBool(core.LooksLikeABuildLabel(args[0].String()))
}
// scopeOrSubincludePackage is like (*scope).contextPackage() package but allows the option to force the use the
// subinclude package
func scopeOrSubincludePackage(s *scope, subinclude bool) (*core.Package, error) {
if subinclude {
pkg := s.subincludePackage()
if pkg == nil {
return nil, errors.New("not in a subinclude scope")
}
return pkg, nil
}
return s.contextPackage(), nil
}
func packageName(s *scope, args []pyObject) pyObject {
const (
labelArgIdx = iota
contextArgIdx
)
pkg, err := scopeOrSubincludePackage(s, args[contextArgIdx].IsTruthy())
if err != nil {
s.Error("cannot call package_name() from this scope: %v", err)
}
if args[labelArgIdx].IsTruthy() {
return pyString(s.parseLabelInPackage(string(args[labelArgIdx].(pyString)), pkg).PackageName)
}
return pyString(pkg.Name)
}
func subrepoName(s *scope, args []pyObject) pyObject {
const (
labelArgIdx = iota
contextArgIdx
)
pkg, err := scopeOrSubincludePackage(s, args[contextArgIdx].IsTruthy())
if err != nil {