-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
1389 lines (1238 loc) · 33.7 KB
/
main.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
package main
//go:generate statik -src=./public -include=*.html,*.css,*.js
import (
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"mime"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/gagliardetto/codebox/scanner"
_ "github.com/gagliardetto/codemill/statik"
"github.com/gagliardetto/codemill/x"
cqljen "github.com/gagliardetto/cqlgen/jen"
"github.com/gagliardetto/feparser"
"github.com/gagliardetto/golang-go/cmd/go/not-internal/get"
"github.com/gagliardetto/golang-go/cmd/go/not-internal/modfetch"
"github.com/gagliardetto/golang-go/cmd/go/not-internal/search"
"github.com/gagliardetto/golang-go/cmd/go/not-internal/web"
"github.com/gagliardetto/request"
. "github.com/gagliardetto/utilz"
"github.com/gin-gonic/gin"
"github.com/rakyll/statik/fs"
"golang.org/x/mod/modfile"
"golang.org/x/tools/go/packages"
"github.com/gagliardetto/codemill/handlers/http/headerwrite"
"github.com/gagliardetto/codemill/handlers/http/redirect"
"github.com/gagliardetto/codemill/handlers/http/responsebody"
"github.com/gagliardetto/codemill/handlers/tainttracking"
"github.com/gagliardetto/codemill/handlers/untrustedflowsource"
)
type M map[string]interface{}
const (
// Use default Golang proxy (???)
proxy = "https://proxy.golang.org/"
)
var (
globalSpec *x.XSpec
)
func main() {
r := gin.Default()
statikFS, err := fs.New()
if err != nil {
Fataln(err)
}
var specFilepath string
var outDir string
var runServer bool
var doGen bool
var doSummary bool
var liveFs bool
flag.StringVar(&specFilepath, "spec", "", "Path to spec file; file will be created if not already existing.")
flag.StringVar(&outDir, "dir", "", "Path to dir where to save generated files.")
flag.BoolVar(&runServer, "http", true, "Run http server.")
flag.BoolVar(&doGen, "gen", true, "Generate code.")
flag.BoolVar(&doSummary, "summary", true, "Output a summary.")
flag.BoolVar(&liveFs, "livefs", false, "Use static assets directly from live FS.")
flag.Parse()
if specFilepath == "" {
// specFilepath is ALWAYS necessary,
// either for knowing from where to load a spec,
// or where to save a new created one.
panic("--spec flag not provided")
}
if outDir == "" {
panic("--dir flag not provided")
}
{ // Add http handlers for static files:
r.GET("/", func(c *gin.Context) {
var reader io.ReadCloser
var err error
if liveFs {
reader, err = os.Open("./public/index.html")
if err != nil {
Q(err)
Abort404(c, err.Error())
return
}
} else {
reader, err = statikFS.Open("/index.html")
if err != nil {
Q(err)
Abort404(c, err.Error())
return
}
}
defer reader.Close()
contents, err := ioutil.ReadAll(reader)
if err != nil {
Q(err)
Abort404(c, err.Error())
return
}
c.Data(200, "text/html; charset=UTF-8", contents)
})
r.GET("/static/:filename", func(c *gin.Context) {
name := c.Param("filename")
if name == "" {
c.AbortWithStatus(400)
return
}
var reader io.ReadCloser
var err error
if liveFs {
reader, err = os.Open(filepath.Join("public", "static", name))
if err != nil {
Q(err)
Abort404(c, err.Error())
return
}
} else {
reader, err = statikFS.Open("/static/" + name)
if err != nil {
c.AbortWithError(400, err)
Q(err)
return
}
}
defer reader.Close()
contents, err := ioutil.ReadAll(reader)
if err != nil {
c.AbortWithError(400, err)
Q(err)
return
}
m := mime.TypeByExtension(filepath.Ext(name))
c.Data(200, Sf("%s; charset=UTF-8", m), contents)
})
}
httpClient := new(http.Client)
{
rt := x.Router()
// Register ModelKind handlers in the router:
{
// untrustedflowsource handler:
err := rt.RegisterHandler(untrustedflowsource.Kind, &untrustedflowsource.Handler{})
if err != nil {
Fatalf("error while registering handler: %s", err)
}
// tainttracking handler:
err = rt.RegisterHandler(tainttracking.Kind, &tainttracking.Handler{})
if err != nil {
Fatalf("error while registering handler: %s", err)
}
// http redirect handler:
err = rt.RegisterHandler(redirect.Kind, &redirect.Handler{})
if err != nil {
Fatalf("error while registering handler: %s", err)
}
// http responsebody handler:
err = rt.RegisterHandler(responsebody.Kind, &responsebody.Handler{})
if err != nil {
Fatalf("error while registering handler: %s", err)
}
// http headerwrite handler:
err = rt.RegisterHandler(headerwrite.Kind, &headerwrite.Handler{})
if err != nil {
Fatalf("error while registering handler: %s", err)
}
}
}
if MustFileExists(specFilepath) {
// If the file exists, try loading the spec:
spec, err := x.TryLoadSpecFromFile(specFilepath, LoadPackage)
if err != nil {
panic(err)
}
globalSpec = spec
} else {
// If the file does NOT exist,
// create a new spec named after the filename:
name := ToCamel(TrimExt(filepath.Base(specFilepath)))
if name == "" {
name = "DefaultSpec"
}
globalSpec = x.NewXSpecWithName(name)
}
onExitCallback := func() {
globalSpec.Lock()
defer globalSpec.Unlock()
globalSpec.RemoveMeta()
// TODO: cleanup before saving.
Infof("Saving spec to %q", MustAbs(specFilepath))
err := SaveAsIndentedJSON(globalSpec, specFilepath)
if err != nil {
panic(err)
}
if doSummary {
Ln("\n", strings.Repeat("-", 60), "\n")
summary, err := x.CreateSummary(globalSpec)
if err != nil {
panic(err)
}
for _, v := range summary {
Ln(v)
}
Ln("\n", strings.Repeat("-", 60), "\n")
}
if !doGen {
Ln(LimeBG(">>> Completed without generation <<<"))
os.Exit(0)
}
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// NOTE: after this point, any modification to globalSpec will be volatile,
// i.e. discarded the instant this program hits os.Exit.
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// Sort stuff for visual convenience in the generated code:
globalSpec.Sort()
// Create output dir if it doesn't exist:
MustCreateFolderIfNotExists(outDir, os.ModePerm)
ts := time.Now()
// Create subfolder for package for generated assets:
packageAssetFolderName := feparser.FormatCodeQlName(globalSpec.Name)
packageAssetFolderPath := path.Join(outDir, packageAssetFolderName)
MustCreateFolderIfNotExists(packageAssetFolderPath, os.ModePerm)
// Create folder for assets generated during this run:
thisRunAssetFolderName := feparser.FormatCodeQlName(globalSpec.Name) + "_" + ts.Format(FilenameTimeFormat)
thisRunAssetFolderPath := path.Join(packageAssetFolderPath, thisRunAssetFolderName)
// Create a new assets folder inside the main assets folder:
MustCreateFolderIfNotExists(thisRunAssetFolderPath, os.ModePerm)
{
// Validate all specs:
for _, mdl := range globalSpec.Models {
handler := x.Router().GetHandler(mdl.Kind)
if handler == nil {
Fatalf(
"handler not found for kind %s",
mdl.Kind,
)
}
{
// Validate provided model:
err := handler.Validate(mdl)
if err != nil {
Fatalf(
"error while validating model %q (kind=%s): %s",
mdl.Name,
mdl.Kind,
err,
)
}
}
}
}
{ // Generate codeql:
cqlFile := cqljen.NewFile()
for _, hdr := range x.CqlFormatHeaderDoc(globalSpec.ListModules()) {
cqlFile.HeaderDoc(hdr)
}
// `go` is always imported:
cqlFile.Import("go")
cqlFile.Doc(x.CqlFormatHeaderDoc(globalSpec.ListModules())...)
cqlFile.Private().Module().Id(feparser.FormatCodeQlName(globalSpec.Name)).BlockFunc(func(moduleGroup *cqljen.Group) {
for _, mdl := range globalSpec.Models {
handler := x.Router().MustGetHandler(mdl.Kind)
{
// Generate codeql with the handler of the ModelKind;
// the handler might generate predicates, classes, etc.
// all within the module block.
err := handler.GenerateCodeQL(cqlFile, mdl, moduleGroup)
if err != nil {
Fatalf(
"error while generating codeql code for model %q (kind=%s): %s",
mdl.Name,
mdl.Kind,
err,
)
}
}
}
})
{
// Save codeql assets:
assetFileName := feparser.FormatCodeQlName(globalSpec.Name) + ".qll"
assetFilepath := path.Join(thisRunAssetFolderPath, assetFileName)
// Create file codeql file:
codeqlFile, err := os.Create(assetFilepath)
if err != nil {
panic(err)
}
defer codeqlFile.Close()
// Write generated codeql to file:
Infof("Saving codeql assets to %q", MustAbs(assetFilepath))
err = cqlFile.Render(codeqlFile)
if err != nil {
panic(err)
}
}
}
{
goTestsFolderPath := path.Join(thisRunAssetFolderPath, "tests")
// Create a folder for Go code:
MustCreateFolderIfNotExists(goTestsFolderPath, os.ModePerm)
// Generate Go code:
for _, mdl := range globalSpec.Models {
handler := x.Router().MustGetHandler(mdl.Kind)
{
err := handler.GenerateGo(goTestsFolderPath, mdl)
if err != nil {
Fatalf(
"error while generating Go code for model %q (kind=%s): %s",
mdl.Name,
mdl.Kind,
err,
)
}
}
}
}
Ln(LimeBG(">>> Generation completed <<<"))
os.Exit(0)
}
var once sync.Once
go Notify(
func(os.Signal) bool {
once.Do(onExitCallback)
return false
},
os.Kill,
os.Interrupt,
)
defer once.Do(onExitCallback)
r.GET("/api/spec", func(c *gin.Context) {
globalSpec.RLock()
defer globalSpec.RUnlock()
c.IndentedJSON(200, globalSpec)
})
r.GET("/api/cached", func(c *gin.Context) {
// List already cached sources:
list := x.GetListCachedSources()
sort.Slice(list, func(i, j int) bool {
return x.FormatPathVersion(list[i].Path, list[i].Version) < x.FormatPathVersion(list[j].Path, list[j].Version)
})
c.IndentedJSON(200, M{"results": list})
})
r.GET("/api/models/kinds", func(c *gin.Context) {
// List available model kinds:
kinds := x.Router().ListModelKinds()
sort.Slice(kinds, func(i, j int) bool {
return kinds[i] < kinds[j]
})
c.IndentedJSON(200, M{"results": kinds})
})
r.POST("/api/spec/models", func(c *gin.Context) {
// Add a new model to the spec:
var req struct {
Name string
Kind x.ModelKind
}
err := c.BindJSON(&req)
if err != nil {
Q(err)
Abort400(c, err.Error())
return
}
req.Name = ToCamel(req.Name)
if len(req.Name) == 0 {
Abort400(c, "Class name not valid")
return
}
created := &x.XModel{
Name: req.Name,
Kind: req.Kind,
}
err = globalSpec.PushModel(created)
if err != nil {
Abort400(c, Sf("Error adding model: %s", err))
return
}
c.IndentedJSON(200, globalSpec)
})
r.PATCH("/api/spec/structs", func(c *gin.Context) {
// Patch a struct, i.e. add/remove a field:
var req struct {
Where struct {
Path string
Version string
Model string
Method string
}
What struct {
StructID string
FieldID string
Value bool
}
}
err := c.BindJSON(&req)
if err != nil {
Q(err)
Abort400(c, err.Error())
return
}
source := x.GetCachedSource(req.Where.Path, req.Where.Version)
if source == nil {
Abort404(c, Sf("Source not found: %s@%s", req.Where.Path, req.Where.Version))
return
}
// Make sure that the struct exist:
st := x.FindStructByID(source, req.What.StructID)
if st == nil {
Abort404(c, Sf("Struct not found: %q", req.What.StructID))
return
}
fld := x.FindFieldByID(st, req.What.FieldID)
if fld == nil {
Abort404(c, Sf("Field not found: %q", req.What.FieldID))
return
}
err = globalSpec.ModifyModelByName(
req.Where.Model,
func(mdl *x.XModel) error {
err := mdl.ModifyMethodByName(
req.Where.Method,
func(mt *x.XMethod) error {
existingSel := mt.GetStructSelector(
req.Where.Path,
req.Where.Version,
req.What.StructID,
)
if existingSel == nil {
// Add a new selector only if the value is true:
if req.What.Value == true {
// If there is no existing selector for the struct,
// then create a new one:
newSel := &x.XSelector{
Kind: x.SelectorKindStruct,
Qualifier: &x.StructQualifier{
BasicQualifier: x.BasicQualifier{
Path: req.Where.Path,
Version: req.Where.Version,
ID: req.What.StructID,
},
TypeName: st.TypeName,
Fields: map[string]*x.FieldMeta{
fld.VarName: {
Name: fld.VarName,
TypeString: fld.TypeString,
KindString: fld.KindString,
},
},
Total: len(st.Fields),
Left: len(st.Fields) - 1,
},
}
mt.Selectors = append(mt.Selectors, newSel)
}
} else {
if req.What.Value {
// Enable field:
existingSel.Fields[fld.VarName] = &x.FieldMeta{
Name: fld.VarName,
TypeString: fld.TypeString,
KindString: fld.KindString,
}
} else {
// Remove field:
delete(existingSel.Fields, fld.VarName)
}
{ // Update counts:
existingSel.Total = len(st.Fields)
existingSel.Left = len(st.Fields) - len(existingSel.Fields)
}
if len(existingSel.Fields) == 0 {
// If all fields are disabled, then remove the selector:
mt.DeleteSelector(
req.Where.Path,
req.Where.Version,
req.What.StructID,
)
}
}
return nil
},
)
if err != nil {
return err
}
return nil
},
)
if err != nil {
Abort400(c, Sf("Error modifying model: %s", err))
return
}
c.IndentedJSON(200, globalSpec)
})
r.PATCH("/api/spec/funcs", func(c *gin.Context) {
// Patch a func (func/type-method/interface-method), i.e. select/unselect its components:
const FlowKeyInp = "Inp"
const FlowKeyOut = "Out"
validFlowKeys := []string{FlowKeyInp, FlowKeyOut}
type FlowValueSet struct {
BlockIndex int
Key string // Either Inp out Out.
Index int // Index on the Func total length.
Value bool
}
type PosValueSet struct {
Index int
Value bool
}
var req struct {
Where struct {
Path string
Version string
Model string
Method string
}
What struct {
FuncID string
}
Pos *PosValueSet
Flow *FlowValueSet
}
err := c.BindJSON(&req)
if err != nil {
Q(err)
Abort400(c, err.Error())
return
}
source := x.GetCachedSource(req.Where.Path, req.Where.Version)
if source == nil {
Abort404(c, Sf("Source not found: %s@%s", req.Where.Path, req.Where.Version))
return
}
// Find the func/type-method/interface-method:
fn := x.FindFuncByID(source, req.What.FuncID)
if fn == nil {
Abort404(c, Sf("Func not found: %q", req.What.FuncID))
return
}
if req.Pos != nil && req.Flow != nil {
Abort400(c, "Non-valid request: req.Pos and req.Flow are both set.")
return
}
if req.Pos != nil {
if req.Pos.Index < 0 || req.Pos.Index >= fn.Len() {
Abort400(c, Sf("req.Pos.Index out of bounds: index=%v, but v.Len() = %v", req.Pos.Index, fn.Len()))
return
}
}
if req.Flow != nil {
// Validate flow Key:
isValidFlowKey := SliceContains(validFlowKeys, req.Flow.Key)
if !isValidFlowKey {
Abort400(c, Sf("Provided req.Flow.Key is not valid: %q", req.Flow.Key))
return
}
// Validate Index:
if req.Flow.Index < 0 || req.Flow.Index >= fn.Len() {
Abort400(c, Sf("req.Flow.Index out of bounds: index=%v, but v.Len() = %v", req.Flow.Index, fn.Len()))
return
}
}
err = globalSpec.ModifyModelByName(
req.Where.Model,
func(mdl *x.XModel) error {
// Currently, only the tainttracking.Handler is the only handler
// that supports flow handling.
if req.Flow != nil && !ModelSupportsFuncFlow(mdl) {
return errors.New("This model does not support func flow qualifiers.")
}
err := mdl.ModifyMethodByName(
req.Where.Method,
func(mt *x.XMethod) error {
meta := x.CompileFuncQualifierElementsMeta(fn)
existingSel := mt.GetFuncSelector(
req.Where.Path,
req.Where.Version,
req.What.FuncID,
)
// Handle Pos:
if req.Pos != nil {
if existingSel == nil {
// Add a new selector only if the value is true:
if req.Pos.Value {
pos := make([]bool, fn.Len())
pos[req.Pos.Index] = req.Pos.Value
// If there is no existing selector,
// then create a new one:
newSel := &x.XSelector{
Kind: x.SelectorKindFunc,
Qualifier: &x.FuncQualifier{
BasicQualifier: x.BasicQualifier{
Path: req.Where.Path,
Version: req.Where.Version,
ID: req.What.FuncID,
},
Pos: pos,
Name: x.GetFuncName(fn),
Elements: meta,
},
}
mt.Selectors = append(mt.Selectors, newSel)
}
} else {
existingSel.Pos[req.Pos.Index] = req.Pos.Value
existingSel.Elements = meta
if AllFalse(existingSel.Pos...) {
// If all false, then remove the selector:
mt.DeleteSelector(
req.Where.Path,
req.Where.Version,
req.What.FuncID,
)
}
}
return nil
}
// Handle Flow:
if req.Flow != nil {
// TODO:
if existingSel == nil {
// Add a new selector only if the value is true:
if req.Flow.Value {
// If there is no existing selector,
// then create a new one:
// If the selector did not exist before,
// then the BlockIndex must be = 0.
if req.Flow.BlockIndex != 0 {
return errors.New("req.Flow.BlockIndex must be zero when first creating.")
}
// Create a new FlowSpec:
flSpec := &x.FlowSpec{
Enabled: true,
Blocks: make([]*x.FlowBlock, 0),
}
// Create a new block:
newBlock := &x.FlowBlock{
Inp: make([]bool, fn.Len()),
Out: make([]bool, fn.Len()),
}
// Set value:
switch req.Flow.Key {
case FlowKeyInp:
newBlock.Inp[req.Flow.Index] = req.Flow.Value
case FlowKeyOut:
newBlock.Out[req.Flow.Index] = req.Flow.Value
}
flSpec.Blocks = append(flSpec.Blocks, newBlock)
newSel := &x.XSelector{
Kind: x.SelectorKindFunc,
Qualifier: &x.FuncQualifier{
BasicQualifier: x.BasicQualifier{
Path: req.Where.Path,
Version: req.Where.Version,
ID: req.What.FuncID,
},
Flows: flSpec,
Name: x.GetFuncName(fn),
Elements: meta,
},
}
// Save selector:
mt.Selectors = append(mt.Selectors, newSel)
}
} else {
if existingSel.Flows == nil {
// TODO: what to do in this case?
return errors.New("Found sel.Flows is nil")
}
if req.Flow.BlockIndex < 0 || req.Flow.BlockIndex > len(existingSel.Flows.Blocks) /* Block is beyond len+1 */ {
return fmt.Errorf(
"req.Flow.BlockIndex is out of bounds: BlockIndex=%v, but blocks.Len() = %v",
req.Flow.BlockIndex,
len(existingSel.Flows.Blocks),
)
}
// TODO:
// - we are len(blocks)+(n>1): error.
// - we are within the existing blocks: modify block.
// - we are len(blocks)+1: create a new block and modify it.
if req.Flow.BlockIndex == len(existingSel.Flows.Blocks) {
// If the BlockIndex is for a not-yet existing block,
// the add one new block.
// This can be done ONLY if it's just one block incremental difference,
// i.e. we cannot edit the 4th block if we have 2 blocks,
// but we can edit the 3rd block if we have 2 blocks (the 3rd block will be created here).
newBlock := &x.FlowBlock{
Inp: make([]bool, fn.Len()),
Out: make([]bool, fn.Len()),
}
existingSel.Flows.Blocks = append(existingSel.Flows.Blocks, newBlock)
}
// Set value:
switch req.Flow.Key {
case FlowKeyInp:
existingSel.Flows.Blocks[req.Flow.BlockIndex].Inp[req.Flow.Index] = req.Flow.Value
case FlowKeyOut:
existingSel.Flows.Blocks[req.Flow.BlockIndex].Out[req.Flow.Index] = req.Flow.Value
}
existingSel.Elements = meta
if x.AllBlocksEmpty(existingSel.Flows.Blocks...) {
existingSel.Flows.Enabled = false
// If all blocks are empty, then remove the selector:
mt.DeleteSelector(
req.Where.Path,
req.Where.Version,
req.What.FuncID,
)
}
}
return nil
}
return nil
},
)
if err != nil {
return err
}
return nil
},
)
if err != nil {
Abort400(c, Sf("Error modifying model: %s", err))
return
}
c.IndentedJSON(200, globalSpec)
})
r.PATCH("/api/spec/funcs/flow/enable", func(c *gin.Context) {
// Enable/disable a flow selector:
type FlowValueSet struct {
Enable bool // Enable selector.
}
var req struct {
Where struct {
Path string
Version string
Model string
Method string
}
What struct {
FuncID string
}
Flow *FlowValueSet
}
err := c.BindJSON(&req)
if err != nil {
Q(err)
Abort400(c, err.Error())
return
}
source := x.GetCachedSource(req.Where.Path, req.Where.Version)
if source == nil {
Abort404(c, Sf("Source not found: %s@%s", req.Where.Path, req.Where.Version))
return
}
// Find the func/type-method/interface-method:
fn := x.FindFuncByID(source, req.What.FuncID)
if fn == nil {
Abort404(c, Sf("Func not found: %q", req.What.FuncID))
return
}
err = globalSpec.ModifyModelByName(
req.Where.Model,
func(mdl *x.XModel) error {
// Currently, only the tainttracking.Handler is the only handler
// that supports flow handling.
if !ModelSupportsFuncFlow(mdl) {
return errors.New("This model does not support func flow qualifiers.")
}
err := mdl.ModifyMethodByName(
req.Where.Method,
func(mt *x.XMethod) error {
meta := x.CompileFuncQualifierElementsMeta(fn)
existingSel := mt.GetFuncSelector(
req.Where.Path,
req.Where.Version,
req.What.FuncID,
)
// Handle Flow:
if existingSel == nil {
// The selctor does not exist.
// TODO: Do nothing, or return a 404??
return nil
} else {
if existingSel.Flows == nil {
// TODO: what to do in this case?
return errors.New("Found sel.Flows is nil")
}
// Set Enabled to true/false:
existingSel.Flows.Enabled = req.Flow.Enable
existingSel.Elements = meta
}
return nil
},
)
if err != nil {
return err
}
return nil
},
)
if err != nil {
Abort400(c, Sf("Error modifying model: %s", err))
return
}
c.IndentedJSON(200, globalSpec)
})
r.DELETE("/api/spec/funcs/flow/blocks", func(c *gin.Context) {
// Delete a block:
type FlowValueSet struct {
BlockIndex int
}
var req struct {
Where struct {
Path string
Version string
Model string
Method string
}
What struct {
FuncID string
}
Flow *FlowValueSet
}
err := c.BindJSON(&req)
if err != nil {
Q(err)
Abort400(c, err.Error())
return
}
source := x.GetCachedSource(req.Where.Path, req.Where.Version)
if source == nil {
Abort404(c, Sf("Source not found: %s@%s", req.Where.Path, req.Where.Version))
return
}
// Find the func/type-method/interface-method:
fn := x.FindFuncByID(source, req.What.FuncID)
if fn == nil {
Abort404(c, Sf("Func not found: %q", req.What.FuncID))
return
}
err = globalSpec.ModifyModelByName(
req.Where.Model,
func(mdl *x.XModel) error {
if !ModelSupportsFuncFlow(mdl) {
return errors.New("This model does not support func flow qualifiers.")
}
err := mdl.ModifyMethodByName(
req.Where.Method,
func(mt *x.XMethod) error {
meta := x.CompileFuncQualifierElementsMeta(fn)
existingSel := mt.GetFuncSelector(
req.Where.Path,
req.Where.Version,
req.What.FuncID,
)
// Handle Flow:
if existingSel == nil {
// The selctor does not exist.
// TODO: Do nothing, or return a 404??
return nil
} else {
if existingSel.Flows == nil {
// TODO: what to do in this case?
return errors.New("Found sel.Flows is nil")
}
// Delete block:
existingSel.Flows.DeleteBlock(req.Flow.BlockIndex)
existingSel.Elements = meta
}
return nil
},
)
if err != nil {
return err
}
return nil
},
)
if err != nil {
Abort400(c, Sf("Error modifying model: %s", err))
return
}
c.IndentedJSON(200, globalSpec)
})
r.PATCH("/api/spec/types", func(c *gin.Context) {
// Patch a type selector:
var req struct {
Where struct {
Path string
Version string
Model string
Method string
}
What struct {
TypeID string
Value bool