-
Notifications
You must be signed in to change notification settings - Fork 7
/
diagram.go
508 lines (478 loc) · 16.2 KB
/
diagram.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
// diagram-creation.go: all the methods attached to the generator object to be used in templating
package catalog
import (
"bytes"
"fmt"
"os"
"path"
"regexp"
"strconv"
"strings"
"sync"
"text/template"
"github.com/pkg/errors"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/renderer/html"
"github.com/anz-bank/protoc-gen-sysl/newsysl"
"github.com/anz-bank/sysl-catalog/pkg/catalogdiagrams"
"github.com/anz-bank/sysl/pkg/cmdutils"
"github.com/anz-bank/sysl/pkg/diagrams"
"github.com/anz-bank/sysl/pkg/integrationdiagram"
"github.com/anz-bank/sysl/pkg/sysl"
"github.com/anz-bank/sysl/pkg/syslutil"
"github.com/anz-bank/sysl/pkg/syslwrapper"
)
var (
ofTypeSymbol = regexp.MustCompile(`(?m)(?:<:)(?:.*)`)
)
const (
plantuml = iota
mermaidjs
)
// All the Create* functions not really create a file other than registering a filepath into "to be created" map list.
// CreateMarkdown is a wrapper function that also converts output markdown to html if in server mode
func (p *Generator) CreateMarkdown(t *template.Template, outputFileName string, i interface{}) error {
var buf bytes.Buffer
if err := t.Execute(&buf, i); err != nil {
return err
}
if err := p.Fs.MkdirAll(path.Dir(outputFileName), os.ModePerm); err != nil {
return err
}
f2, err := p.Fs.Create(outputFileName)
if err != nil {
return err
}
out := buf.Bytes()
var converted bytes.Buffer
if p.Format == "html" && !p.DisableCss {
md := goldmark.New(
goldmark.WithExtensions(extension.GFM),
goldmark.WithRendererOptions(
html.WithUnsafe(),
),
)
if err := md.Convert(out, &converted); err != nil {
return errors.Wrap(err, "Error converting markdown to html:")
}
raw := string(converted.Bytes())
raw = strings.ReplaceAll(raw, "README.md", p.OutputFileName)
out = []byte(header + raw + style + endTags)
}
if _, err = f2.Write(out); err != nil {
return err
}
return nil
}
func (p *Generator) CreateIntegrationDiagram(m *sysl.Module, title string, EPA bool) string {
if p.Mermaid {
return p.CreateIntegrationDiagramMermaid(m, title, EPA)
}
return p.CreateIntegrationDiagramPlantuml(m, title, EPA)
}
//TODO @ashwinsajiv: fill out this function to generate mermaid integration diagrams
func (p *Generator) CreateIntegrationDiagramMermaid(m *sysl.Module, title string, EPA bool) string {
return "" //p.CreateFile("plantumlString", mermaidjs, "title", "integration.Output+p.Ext")
}
// CreateIntegrationDiagram creates an integration diagram and returns the filename
func (p *Generator) CreateIntegrationDiagramPlantuml(m *sysl.Module, title string, EPA bool) string {
type intsCmd struct {
diagrams.Plantumlmixin
cmdutils.CmdContextParamIntgen
}
integration := intsCmd{}
projectApp := createProjectApp(m.Apps)
project := "__TEMP__"
defer delete(p.RootModule.GetApps(), project)
p.RootModule.GetApps()[project] = projectApp
integration.Project = project
integration.Output = "integration" + TernaryOperator(EPA, "EPA", "").(string)
integration.Title = title
integration.EPA = EPA
integration.Clustered = true
result, err := integrationdiagram.GenerateIntegrations(&integration.CmdContextParamIntgen, p.RootModule, p.Log)
if err != nil {
p.Log.Error("Error creating integration diagram:", err)
os.Exit(1)
}
plantumlString := result[integration.Output]
return p.CreateFile(plantumlString, plantuml, integration.Output+p.Ext)
}
// CreateSequenceDiagram creates an sequence diagram and returns the filename
func (p *Generator) CreateSequenceDiagram(appName string, endpoint *sysl.Endpoint) string {
m := p.RootModule
call := fmt.Sprintf("%s <- %s", appName, endpoint.GetName())
plantumlString, err := CreateSequenceDiagram(m, call)
if err != nil {
p.Log.Error("Error creating sequence diagram:", err)
os.Exit(1)
return ""
}
return p.CreateFile(plantumlString, plantuml, appName, endpoint.GetName()+p.Ext)
}
type Param interface {
Typer
GetName() string
}
// CreateParamDataModel creates a parameter data model and returns a filename
func (p *Generator) CreateParamDataModel(app *sysl.Application, param Param) string {
var appName, typeName, aliasTypeName string
var getRecursive bool
aliasTypeName = param.GetName()
appName, typeName = GetAppTypeName(param)
if aliasTypeName == "" {
aliasTypeName = typeName
}
if appName == "" {
appName = path.Join(app.GetName().GetPart()...)
}
if appName == "primitive" {
getRecursive = false
} else {
getRecursive = true
}
return p.CreateAliasedTypeDiagram(appName, typeName, aliasTypeName, param.GetType(), getRecursive)
}
// GetReturnType converts an application and a param into a type, useful for getting attributes.
func (p *Generator) GetParamType(app *sysl.Application, param *sysl.Param) *sysl.Type {
var appName, typeName string
appName, typeName = GetAppTypeName(param)
if appName == "" {
appName = path.Join(app.GetName().GetPart()...)
}
return p.RootModule.Apps[appName].GetTypes()[typeName]
}
// GetReturnType converts an endpoint and a statement into a type, useful for getting attributes.
func (p *Generator) GetReturnType(endpoint *sysl.Endpoint, stmnt *sysl.Statement) *sysl.Type {
var appName, typeName string
ret := stmnt.GetRet()
if ret == nil {
return nil
}
t := strings.ReplaceAll(ofTypeSymbol.FindString(ret.GetPayload()), "<: ", "")
if strings.Contains(t, "sequence of") {
t = strings.ReplaceAll(t, "sequence of ", "")
}
if split := strings.Split(t, "."); len(split) > 1 {
appName = split[0]
typeName = split[1]
} else {
typeName = split[0]
}
if appName == "" {
appName = strings.Join(endpoint.GetSource().GetPart(), "")
}
return p.RootModule.GetApps()[appName].GetTypes()[typeName]
}
// CreateReturnDataModel creates a return data model and returns a filename, or empty string if it wasn't a return statement.
func (p *Generator) CreateReturnDataModel(appname string, stmnt *sysl.Statement, endpoint *sysl.Endpoint) string {
var sequence, getRecursive bool
var typeref *sysl.Type
var appName, typeName string
ret := stmnt.GetRet()
if ret == nil {
return ""
}
t := strings.ReplaceAll(ofTypeSymbol.FindString(ret.Payload), "<: ", "")
if strings.Contains(t, "sequence of") {
t = strings.ReplaceAll(t, "sequence of ", "")
sequence = true
}
if split := strings.Split(t, "."); len(split) > 1 {
appName = split[0]
typeName = split[1]
} else {
appName = appname
typeName = split[0]
}
if sequence {
newSequenceName := endpoint.GetName() + "ReturnVal"
newAppName := appname
defer delete(p.RootModule.GetApps()[newAppName].GetTypes(), newSequenceName)
p.RootModule.GetApps()[newAppName].GetTypes()[newSequenceName] = &sysl.Type{
Type: &sysl.Type_Tuple_{
Tuple: &sysl.Type_Tuple{
AttrDefs: map[string]*sysl.Type{"sequence": {Type: &sysl.Type_Sequence{
Sequence: newsysl.Type(typeName, appName)},
},
},
},
},
}
typeref = NewTypeRef(newAppName, newSequenceName)
} else {
typeref = NewTypeRef(appName, typeName)
}
if _, ok := p.RootModule.Apps[appName]; !ok {
return ""
}
if syslwrapper.IsPrimitive(typeName) {
getRecursive = false
typeref = syslwrapper.MakePrimitive(typeName)
} else {
getRecursive = true
}
return p.CreateTypeDiagram(appName, typeName, typeref, getRecursive)
}
// CreateTypeDiagram creates a data model diagram and returns the filename
// It handles recursively getting the related types, or for primitives, just returns the
func (p *Generator) CreateTypeDiagram(appName string, typeName string, t *sysl.Type, recursive bool) string {
return p.CreateAliasedTypeDiagram(appName, typeName, typeName, t, recursive)
}
func (p *Generator) CreateAliasedTypeDiagram(appName, typeName, typeAlias string, t *sysl.Type, recursive bool) string {
m := p.RootModule
var plantumlString string
if recursive {
relatedTypes := catalogdiagrams.RecursivelyGetTypes(
appName,
map[string]*catalogdiagrams.TypeData{
typeAlias: catalogdiagrams.NewTypeData(typeAlias, NewTypeRef(appName, typeName)),
}, m,
)
plantumlString = catalogdiagrams.GenerateDataModel(appName, relatedTypes)
if _, ok := p.RootModule.GetApps()[appName]; !ok {
return ""
}
// Handle Empty
if len(relatedTypes) == 0 {
return ""
}
} else {
plantumlString = catalogdiagrams.GenerateDataModel(
appName,
map[string]*catalogdiagrams.TypeData{typeAlias: catalogdiagrams.NewTypeData(typeAlias, t)},
)
}
return p.CreateFile(
plantumlString, plantuml, appName,
typeName+TernaryOperator(
recursive,
TernaryOperator(typeAlias == typeName, "", typeAlias),
TernaryOperator(typeAlias == typeName, "simple", typeAlias)).(string)+p.Ext)
}
// CreateFileName returns the absolute and relative filepaths
func CreateFileName(dir string, elems ...string) (string, string) {
var absolutefilePath, filename string
for i, e := range elems {
if i == len(elems)-1 {
filename = strings.ToLower(SanitiseOutputName(e))
absolutefilePath = path.Join(absolutefilePath, filename)
break
}
absolutefilePath = path.Join(absolutefilePath, SanitiseOutputName(e))
}
if dir != "" {
dir += "/"
}
return path.Join(dir, absolutefilePath), dir
}
// CreateRedoc registers a file that needs to be created when the input source context has extension .json or .yaml
func (p *Generator) CreateRedoc(sourceContext *sysl.SourceContext, appName string) string {
if !IsOpenAPIFile(sourceContext) || !p.Redoc || strings.Contains(sourceContext.GetFile(), "github") {
return ""
}
absPath, _ := CreateFileName(p.CurrentDir, appName+".redoc.html")
absPath = path.Join(p.OutputDir, absPath)
var err error
p.RedocFilesToCreate[absPath], err = BuildSpecURL(sourceContext)
if err != nil {
p.Log.Error(err)
}
link, _ := CreateFileName("", appName+".redoc.html")
return link
}
func root(p string) string {
this := strings.Split(p, "/")
ret := ""
for _ = range this {
ret += "../"
}
return ret
}
// CreateFile registers a file that needs to be created in p, or returns the embedded img tag if in server mode
func (p *Generator) CreateFile(contents string, diagramType int, elems ...string) string {
var absFilePath, currentDir string
absFilePath, currentDir = CreateFileName(p.CurrentDir, elems...)
var targetMap map[string]string
mutex := &sync.RWMutex{}
var err error
switch diagramType {
case plantuml:
if !strings.Contains(p.PlantumlService, ".jar") {
contents, err = PlantUMLURL(p.PlantumlService, contents)
}
mutex.Lock()
targetMap = p.FilesToCreate
mutex.Unlock()
case mermaidjs:
mutex.Lock()
targetMap = p.MermaidFilesToCreate
mutex.Unlock()
default:
panic("Wrong diagram type specified")
}
if err != nil {
p.Log.Error("Error creating file:", err)
os.Exit(1)
return ""
}
newFileName := absFilePath
for i := 0; ; i++ {
mutex.RLock()
diagram, ok := targetMap[newFileName]
mutex.RUnlock()
if !ok || diagram == contents {
break
}
newFileName = strings.ReplaceAll(absFilePath, p.Ext, strconv.Itoa(i)+p.Ext)
}
absFilePath = newFileName
// if p.ImageTags: return image tag from plantUML service
if p.ImageTags && diagramType == plantuml && !strings.Contains(p.PlantumlService, ".jar") {
return contents
}
if p.ImageDest != "" {
absFilePath = path.Join(p.ImageDest, strings.ReplaceAll(absFilePath, "/", "-"))
mutex.Lock()
targetMap[absFilePath] = contents
mutex.Unlock()
return path.Join(root(currentDir), absFilePath)
}
mutex.Lock()
targetMap[path.Join(p.OutputDir, absFilePath)] = contents
mutex.Unlock()
return strings.Replace(absFilePath, currentDir, "", 1)
}
// GenerateDataModel generates a data model for all of the types in app
func (p *Generator) GenerateDataModel(app *sysl.Application) string {
appName := strings.Join(app.GetName().GetPart(), "")
plantumlString := catalogdiagrams.GenerateDataModel(appName, catalogdiagrams.FromSyslTypeMap(appName, app.GetTypes()))
if _, ok := p.RootModule.GetApps()[appName]; !ok {
return ""
}
return p.CreateFile(plantumlString, plantuml, appName, "types"+p.Ext)
}
func (p *Generator) getProjectApp(m *sysl.Module) (*sysl.Application, map[string]string) {
includedProjects := Filter(
SortedKeys(m.Apps),
func(i string) bool {
return syslutil.HasPattern(m.GetApps()[i].GetAttrs(), "project") &&
path.Base(m.GetApps()[i].SourceContext.File) == path.Base(p.SourceFileName)
},
)
if len(includedProjects) > 0 {
set := make(map[string]string)
app := m.GetApps()[includedProjects[0]]
for _, e := range app.GetEndpoints() {
if syslutil.HasPattern(e.GetAttrs(), "ignore") {
continue
}
for _, e2 := range e.GetStmt() {
set[e2.GetAction().GetAction()] = e.Name
}
}
return m.GetApps()[includedProjects[0]], set
}
return nil, nil
}
// ModuleAsMacroPackage returns "macro packages" that map to the endpoints on the "project" application
/*
project[~project]: <-- first map
FirstDivision: <-- ["FirstDivision"]:
package1 <-- all apps in this package will be contained in this module
package2 <-- same with this one
SecondDivision: <-- ["SecondDivision"]:
package3 <-- You get the point
*/
func (p *Generator) ModuleAsMacroPackage(m *sysl.Module) map[string]*sysl.Module {
packages := make(map[string]*sysl.Module)
_, includedProjects := p.getProjectApp(m)
for _, key := range SortedKeys(m.GetApps()) {
app := m.GetApps()[key]
packageName := GetPackageName(p.RootModule, app)
if packageName == "" {
packageName = key
}
// what endpoint on the "project app" are we on?
projectEndpoint, ok := includedProjects[packageName]
if len(includedProjects) > 0 && !ok || (projectEndpoint == "") {
continue
}
if syslutil.HasPattern(app.GetAttrs(), "ignore") || syslutil.HasPattern(app.GetAttrs(), "project") {
continue
}
if _, ok := packages[projectEndpoint]; !ok {
packages[projectEndpoint] = newsysl.Module()
}
if _, ok := packages[projectEndpoint]; !ok {
packages[projectEndpoint] = &sysl.Module{Apps: map[string]*sysl.Application{}}
}
packages[projectEndpoint].GetApps()[strings.Join(app.GetName().GetPart(), "")] = app
}
return packages
}
// MacroPackages executes the markdown for a MacroPackage and returns a slice of the rows
func (p *Generator) MacroPackages(module *sysl.Module) []string {
defer p.resetTempVars()
MacroPackages := p.ModuleAsMacroPackage(module)
for macroPackageName, macroPackage := range MacroPackages {
fileName := markdownName(p.OutputFileName, macroPackageName)
macroPackageFileName := path.Join(p.OutputDir, macroPackageName, fileName)
p.CurrentDir = macroPackageName
p.TempDir = macroPackageName // this is for p.Packages()
p.Title = macroPackageName
p.Links = map[string]string{
"Back": "../" + p.OutputFileName,
}
p.Module = macroPackage
err := p.CreateMarkdown(p.Templates[1], macroPackageFileName, p)
if err != nil {
p.Log.Error("Error generating project table:", err)
os.Exit(1)
}
}
return SortedKeys(MacroPackages)
}
func (p *Generator) resetTempVars() {
p.CurrentDir = p.TempDir
p.TempDir = ""
}
// Packages executes the markdown for a package and returns a slice of the rows
func (p *Generator) Packages(m *sysl.Module) []string {
defer p.resetTempVars()
MacroPackages := p.ModuleAsPackages(m)
for packageName, pkg := range MacroPackages {
p.CurrentDir = path.Join(p.TempDir, packageName)
fileName := markdownName(p.OutputFileName, packageName)
fullOutputName := path.Join(p.OutputDir, p.CurrentDir, fileName)
if err := p.CreateMarkdown(p.Templates[len(p.Templates)-1], fullOutputName, pkg); err != nil {
p.Log.Error("error in generating "+fullOutputName, err)
}
}
return SortedKeys(MacroPackages)
}
// ModuleAsPackages returns a map of [packagename]*sysl.Module
func (p *Generator) ModuleAsPackages(m *sysl.Module) map[string]*sysl.Module {
packages := make(map[string]*sysl.Module)
_, includedProjects := p.getProjectApp(m)
for _, key := range SortedKeys(m.GetApps()) {
app := m.GetApps()[key]
packageName, _ := GetAppPackageName(app)
if packageName == "" {
packageName = key
}
if _, ok := includedProjects[packageName]; len(includedProjects) > 0 && !ok {
continue
}
packageName = GetPackageName(p.RootModule, app)
if syslutil.HasPattern(app.GetAttrs(), "ignore") || syslutil.HasPattern(app.GetAttrs(), "project") {
continue
}
if _, ok := packages[packageName]; !ok {
packages[packageName] = &sysl.Module{Apps: map[string]*sysl.Application{}}
}
packages[packageName].GetApps()[strings.Join(app.GetName().GetPart(), "")] = app
}
return packages
}