-
Notifications
You must be signed in to change notification settings - Fork 7
/
generator.go
270 lines (250 loc) · 8.38 KB
/
generator.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
// generator.go: struct for converting sysl modules to documentation (Generator)
package catalog
import (
"fmt"
"os"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"text/template"
"time"
"github.com/cheggaaa/pb/v3"
"github.com/iancoleman/strcase"
"github.com/anz-bank/sysl/pkg/syslutil"
"github.com/sirupsen/logrus"
"github.com/anz-bank/sysl/pkg/sysl"
"github.com/spf13/afero"
)
var typeMaps = map[string]string{"md": "README.md", "markdown": "README.md", "html": "index.html"}
// Generator is the contextual object that is used in the markdown generation
type Generator struct {
FilesToCreate map[string]string
MermaidFilesToCreate map[string]string
RedocFilesToCreate map[string]string
SourceFileName string
ProjectTitle string
RootModule *sysl.Module
LiveReload bool // Add live reload javascript to html
ImageTags bool // embedded plantuml img tags, or generated svgs
DisableCss bool // used for rendering raw markdown
DisableImages bool // used for omitting image creation
Mermaid bool
Redoc bool // used for generating redoc for openapi specs
ImageDest string // Output all images into this folder is set
Format string // "html" or "markdown" or "" if custom
Ext string
OutputFileName string
PlantumlService string
Log *logrus.Logger
Fs afero.Fs
errs []error // Any errors that stop from rendering will be output to the browser
Templates []*template.Template
StartTemplateIndex int
// All of these are used in markdown generation
CurrentDir string
TempDir string
Module *sysl.Module
Title string
OutputDir string
Links map[string]string
Server bool
}
type SourceCoder interface {
Attr
GetSourceContext() *sysl.SourceContext
}
// RootPath appends CurrentDir to output
func (p *Generator) SourcePath(a SourceCoder) string {
rootDir := rootDirectory(path.Join(p.OutputDir, p.CurrentDir))
if source_path := Attribute(a, "source_path"); source_path != "" {
return rootDir + Attribute(a, "source_path")
}
return path.Join(rootDir, a.GetSourceContext().File)
}
// NewProject generates a Generator object, fs and outputDir are optional if being used for a web server.
func NewProject(
titleAndFileName, plantumlService, outputType string,
log *logrus.Logger,
module *sysl.Module,
fs afero.Fs, outputDir string, mermaidEnabled bool) *Generator {
p := Generator{
ProjectTitle: titleAndFileName,
SourceFileName: titleAndFileName,
OutputDir: outputDir,
OutputFileName: typeMaps[strings.ToLower(outputType)],
Format: strings.ToLower(outputType),
Log: log,
RootModule: module,
PlantumlService: plantumlService,
FilesToCreate: make(map[string]string),
RedocFilesToCreate: make(map[string]string),
Fs: fs,
Ext: ".svg",
Mermaid: mermaidEnabled,
}
//if strings.Contains(p.PlantumlService, ".jar") {
// _, err := os.Open(p.PlantumlService)
// if err != nil {
// p.Log.Error("Error adding plantumlenv:", err)
// }
//}
if module != nil && len(p.ModuleAsMacroPackage(module)) <= 1 {
p.StartTemplateIndex = 1 // skip the MacroPackageProject
}
return p.WithTemplateString(MacroPackageProject, ProjectTemplate, NewPackageTemplate)
}
// WithTemplateFileNames loads template strings into project and package of p respectively
func (p *Generator) WithTemplateString(tmpls ...string) *Generator {
for i, e := range tmpls {
tmpl, err := template.New(strconv.Itoa(i)).Funcs(p.GetFuncMap()).Parse(e)
if err != nil {
p.Log.Error("Error registering template:", err)
return nil
}
p.Templates = append(p.Templates, tmpl)
}
return p
}
func (p *Generator) WithTemplateFs(fs afero.Fs, fileNames ...string) *Generator {
var tmpls []string
if len(fileNames) == 0 || fileNames[0] == "" {
return p
}
for _, e := range fileNames {
bytes, err := afero.ReadFile(fs, e)
if err != nil {
p.Log.Error("Error opening template file:", p)
os.Exit(1)
}
tmpls = append(tmpls, string(bytes))
}
p.Templates = make([]*template.Template, 0, 2)
p.StartTemplateIndex = 0
return p.WithTemplateString(tmpls...)
}
func (p *Generator) SetOptions(disableCss, disableImages, imageTags, redoc bool, readmeName string, ImageDest string) *Generator {
p.Redoc = redoc
p.DisableCss = disableCss
p.DisableImages = disableImages || imageTags
p.ImageTags = imageTags
p.ImageDest = ImageDest
if readmeName != "" {
p.OutputFileName = readmeName
}
return p
}
// Run Executes a project and generates markdown and diagrams to a given filesystem.
func (p *Generator) Run() {
p.Title = p.ProjectTitle
fileName := markdownName(p.OutputFileName, path.Base(p.ProjectTitle))
p.Module = p.RootModule
if err := p.CreateMarkdown(p.Templates[p.StartTemplateIndex], path.Join(p.OutputDir, fileName), p); err != nil {
p.Log.Error("Error creating project markdown:", err)
}
var wg sync.WaitGroup
var progress *pb.ProgressBar
var completedDiagrams int64
var diagramCreator = func(inMap map[string]string, f func(fs afero.Fs, filename string, data string) error) {
for fileName, contents := range inMap {
wg.Add(1)
go func(fileName, contents string) {
var err = f(p.Fs, fileName, contents)
if err != nil {
p.Log.Error("Error generating file:", err)
os.Exit(1)
}
if progress != nil {
progress.Increment()
}
wg.Done()
completedDiagrams++
}(fileName, contents)
}
}
if p.Mermaid {
progress = pb.StartNew(len(p.MermaidFilesToCreate))
fmt.Println("Generating Mermaid diagrams:")
diagramCreator(p.MermaidFilesToCreate, GenerateAndWriteMermaidDiagram)
}
if p.Redoc {
progress = pb.StartNew(len(p.RedocFilesToCreate))
logrus.Info("Generating Redoc files")
diagramCreator(p.RedocFilesToCreate, GenerateAndWriteRedoc)
}
if (p.ImageTags || p.DisableImages) && !p.Redoc {
logrus.Info("Skipping Image creation")
return
}
fmt.Println("Generating diagrams:")
if strings.Contains(p.PlantumlService, ".jar") {
if !p.Server {
diagramCreator(p.FilesToCreate, p.PUMLFile)
start := time.Now()
if err := PlantUMLJava(p.PlantumlService, p.OutputDir); err != nil {
p.Log.Error(err)
}
elapsed := time.Since(start)
fmt.Println("Generating took ", elapsed)
}
} else {
progress = pb.StartNew(len(p.FilesToCreate) + len(p.MermaidFilesToCreate) + len(p.RedocFilesToCreate))
progress.SetCurrent(completedDiagrams)
diagramCreator(p.FilesToCreate, HttpToFile)
}
wg.Wait()
fmt.Println(p.OutputDir)
if progress != nil {
progress.Finish()
}
}
func markdownName(s, candidate string) string {
if strings.Contains(s, "{{.Title}}") {
candidate = SanitiseOutputName(candidate)
return strings.ReplaceAll(s, "{{.Title}}", candidate)
}
return s
}
func Last(i interface{}, ind int) bool {
return ind == len(SortedKeys(i))-1
}
func Remove(s string, old ...string) string {
for _, e := range old {
re := regexp.MustCompile(e)
s = re.ReplaceAllString(s, "")
}
return s
}
// GetFuncMap returns the funcs that are used in diagram generation.
func (p *Generator) GetFuncMap() template.FuncMap {
return template.FuncMap{
"CreateIntegrationDiagram": p.CreateIntegrationDiagram,
"CreateSequenceDiagram": p.CreateSequenceDiagram,
"CreateParamDataModel": p.CreateParamDataModel,
"CreateReturnDataModel": p.CreateReturnDataModel,
"CreateTypeDiagram": p.CreateTypeDiagram,
"CreateRedoc": p.CreateRedoc,
"GenerateDataModel": p.GenerateDataModel,
"GetParamType": p.GetParamType,
"GetReturnType": p.GetReturnType,
"SourcePath": p.SourcePath,
"Packages": p.Packages,
"MacroPackages": p.MacroPackages,
"hasPattern": syslutil.HasPattern,
"ModuleAsPackages": p.ModuleAsPackages,
"ModulePackageName": ModulePackageName,
"SortedKeys": SortedKeys,
"Attribute": Attribute,
"Fields": Fields,
"FieldType": FieldType,
"SanitiseOutputName": SanitiseOutputName,
"ToLower": strings.ToLower,
"ToCamel": strcase.ToCamel,
"Remove": Remove,
"ToTitle": strings.ToTitle,
"Base": filepath.Base,
"Last": Last,
}
}