-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
372 lines (331 loc) · 9.66 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
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/dustismo/heavyfishdesign/dom"
"github.com/dustismo/heavyfishdesign/dynmap"
"github.com/dustismo/heavyfishdesign/parser"
"github.com/dustismo/heavyfishdesign/path"
"github.com/dustismo/heavyfishdesign/util"
"github.com/sergi/go-diff/diffmatchpatch"
)
var FileExtension = "hfd"
func main() {
// initialize
// various flags
renderFilename := flag.String("path", "", "Path to the file to render")
outputFile := flag.String("output_file", "", "File name to save")
renderDirectory := flag.String("render_dir", "designs/", "The Directory to render (recursively)")
outputDirectory := flag.String("output_dir", "", "The Directory to render into")
compareDirectory := flag.String("compare_dir", "designs_rendered", "The Directory to compare the current render to")
if len(os.Args) < 2 {
fmt.Printf("Usage: \n \t$ run main.go [serve|render|render_all|diff_test|designs_updated]\n")
return
}
command := os.Args[1]
err := flag.CommandLine.Parse(os.Args[2:])
if err != nil {
log.Fatalf("Error %s", err.Error())
return
}
// the command
parser.InitContext()
if command == "serve" {
http.Handle("/json", http.HandlerFunc(processRequest))
err := http.ListenAndServe(":2003", nil)
if err != nil {
log.Fatal("ListenAndServe:", err)
}
} else if command == "render" {
logger := util.NewLog()
rfn := os.Args[2]
if len(*renderFilename) > 0 {
rfn = *renderFilename
}
if len(rfn) == 0 {
log.Fatalf("Render filename is required")
return
}
planset, err := renderPlanSet(rfn, dynmap.New(), logger)
if err != nil {
log.Fatalf("Error during planset render: %s\n", err.Error())
return
}
outFile := createFilename(*outputFile, rfn)
err = save(planset, outFile, logger)
if err != nil {
fmt.Printf("Error during save: %s\n", err.Error())
return
}
} else if command == "render_all" {
logger := util.NewLog()
err := RenderAll(*renderDirectory, *outputDirectory, logger)
if err != nil {
logger.Errorf("error %s", err.Error())
return
}
} else if command == "designs_updated" {
logger := util.NewLog()
// clear out the designs rendered directory
util.ClearDir("designs_rendered", "svg")
err := RenderAll("designs", "designs_rendered", logger)
if err != nil {
logger.Errorf("error %s", err.Error())
return
}
} else if command == "diff_test" {
logger := util.NewLog()
logger.LogToStdOut = util.Fatal
if outputDirectory == nil || len(*outputDirectory) == 0 {
od, err := ioutil.TempDir("", "hfd_diff_test")
if err != nil {
logger.Errorf("error %s", err.Error())
return
}
outputDirectory = &od
}
err := RenderAll(*renderDirectory, *outputDirectory, logger)
if err != nil {
fmt.Printf("error %s", err.Error())
return
}
CompareDirectories(*compareDirectory, *outputDirectory, "svg", logger)
diffCount := 0
if logger.HasErrors() {
for _, msg := range logger.Messages {
if msg.MustBool("bad_diff", false) {
diffCount = diffCount + 1
fmt.Printf("*******************\n")
fmt.Printf("file1: %s\n", msg.MustString("file1", ""))
fmt.Printf("file2: %s\n", msg.MustString("file2", ""))
fmt.Printf("diff: \n%s\n", msg.MustString("diff", ""))
fmt.Printf("*******************\n")
}
}
}
fmt.Printf("\n\nTotal files with differences: %d\n", diffCount)
for _, msg := range logger.Messages {
if msg.MustBool("bad_diff", false) {
fmt.Printf("\t%s\n", msg.MustString("file1", ""))
}
}
} else if command == "svg" {
logger := util.NewLog()
logger.LogToStdOut = util.Info
} else {
fmt.Printf("Usage: \n \t$ run main.go [serve|render|render_all|diff_test|designs_updated]\n")
}
}
func CompareDirectories(left string, right string, extension string, logger *util.HfdLog) {
filesLeft, err := util.FileList(left, extension)
if err != nil {
logger.Errorf("Unable to list files in directory %s: %s", left, err.Error())
return
}
filesRight, err := util.FileList(right, extension)
if err != nil {
logger.Errorf("Unable to list files in directory %s: %s", right, err.Error())
return
}
for _, l := range filesLeft {
loggerL := logger.NewChild()
loggerL.StaticFields.Put("filename", l)
_, lBase := filepath.Split(l)
// now look for the same file base name in the right side
found := false
for _, r := range filesRight {
if !found {
_, rBase := filepath.Split(r)
if rBase == lBase {
// now compare files
loggerL.Infof("Comparing files:\n\t%s\n\t%s", l, r)
lBytes, err := ioutil.ReadFile(l)
if err != nil {
loggerL.Errorf("error loading %s: %s", l, err.Error())
}
rBytes, err := ioutil.ReadFile(r)
if err != nil {
loggerL.Errorf("error loading %s: %s", r, err.Error())
}
diff := diffmatchpatch.New()
diffs := diff.DiffMain(string(lBytes), string(rBytes), false)
if !IsEqualDiff(diffs) {
loggerL.Errorf("Files not equal: bytes not equal")
loggerL.Errorfd(dynmap.Wrap(map[string]interface{}{
"bad_diff": true,
"diff": diff.DiffPrettyText(diffs),
"file1": l,
"file2": r,
}), diff.DiffPrettyText(diffs))
} else {
loggerL.Infof("Files are equal!")
}
found = true
}
}
}
if !found {
loggerL.Errorf("Unable to find file %s in directory %s", lBase, right)
}
}
}
func IsEqualDiff(diffs []diffmatchpatch.Diff) bool {
eq := true
for _, d := range diffs {
if d.Type != diffmatchpatch.DiffEqual {
eq = false
}
}
return eq
}
// creates the directory listed if it does not already exist
func CreateDir(dir string) error {
return os.MkdirAll(dir, os.ModePerm)
}
func RenderAll(renderDir, outputDir string, logger *util.HfdLog) error {
filenames, err := util.FileList(renderDir, FileExtension)
if err != nil {
logger.Errorf("Error during render_all: %s\n", err.Error())
return err
}
err = CreateDir(outputDir)
if err != nil {
logger.Errorf("Error creating directory %s: %s\n", outputDir, err.Error())
return err
}
for _, rf := range filenames {
planLogger := logger.NewChild()
planLogger.StaticFields.Put("filename", rf)
planset, err := renderPlanSet(rf, dynmap.New(), planLogger)
if err != nil {
planLogger.Errorf("Error during planset %s : %s\n", rf, err.Error())
} else {
outFile := createFilename(outputDir, rf)
err = save(planset, outFile, planLogger)
if err != nil {
planLogger.Errorf("Error during save %s : %s\n", rf, err.Error())
}
}
}
return nil
}
func renderPlanSet(filename string, params *dynmap.DynMap, logger *util.HfdLog) (*dom.PlanSet, error) {
logger.Infof("RENDERING: %s\n", filename)
b, err := ioutil.ReadFile(filename) // just pass the file name
if err != nil {
return nil, err
}
json := string(b) // convert content to a 'string'
dm, err := dynmap.ParseJSON(json)
if err != nil {
return nil, err
}
docParams := dm.MustDynMap("params", dynmap.New()).Clone().Merge(params)
dm.Put("params", docParams)
doc, err := dom.ParseDocument(dm, logger)
if err != nil {
return nil, err
}
planset := dom.NewPlanSet(doc)
context := dom.RenderContext{
Origin: path.NewPoint(0, 0),
Cursor: path.NewPoint(0, 0),
}
err = planset.Init(context)
return planset, err
}
// construct a suitable saveFile name from the give path + document name
// for instance:
// filepath = "/home/my_document/"
// docuPath = "/home/designs/box_name.hfd"
// = /home/my_document/box_name_000.svg
func createFilename(filePath string, documentPath string) string {
_, dcFn := filepath.Split(documentPath)
// if no filePath is specified then use the documentpath
if len(filePath) == 0 {
// take document filename, strip suffix, then use that.
// local directory in that case.
return strings.TrimSuffix(dcFn, filepath.Ext(documentPath))
}
fpDir, fpFn := filepath.Split(filePath)
if IsDir(filePath) {
// need to make sure fbFn is not a directory
fpDir = filepath.Clean(filePath)
fpFn = ""
}
if len(fpFn) == 0 {
// filepath directory but not file
fp := strings.TrimSuffix(dcFn, filepath.Ext(dcFn))
return filepath.Join(fpDir, fp)
}
return strings.TrimSuffix(filePath, filepath.Ext(filePath))
}
// see if this path is an existing directory
func IsDir(filePath string) bool {
f, err := os.Open(filePath)
if err == nil {
defer f.Close()
stat, err := f.Stat()
if err == nil {
return stat.IsDir()
}
}
return false
}
func save(planset *dom.PlanSet, saveFile string, logger *util.HfdLog) error {
svgDocs := planset.SVGDocuments()
context := dom.RenderContext{
Origin: path.NewPoint(0, 0),
Cursor: path.NewPoint(0, 0),
Log: logger,
}
for i, svgDoc := range svgDocs {
fn := fmt.Sprintf("%s_%03d.svg", saveFile, i)
f, err := os.Create(fn)
if err != nil {
return err
}
defer f.Close()
logger.Infof("SAVING: %s\n", fn)
svgDoc.WriteSVG(context, f)
}
return nil
}
func processRequest(w http.ResponseWriter, req *http.Request) {
params := dynmap.New()
err := req.ParseForm()
if err != nil {
println(err.Error())
return
}
params.UnmarshalUrlValues(req.Form)
logger := util.NewLog()
filename := params.MustString("file", "dom/testdata/box_test.hfd")
planset, err := renderPlanSet(filename, params, logger)
if err != nil {
logger.Errorf("Error during render: %s\n", err.Error())
return
}
svgDocs := planset.SVGDocuments()
context := dom.RenderContext{
Origin: path.NewPoint(0, 0),
Cursor: path.NewPoint(0, 0),
}
svgDocs[params.MustInt("index", 0)].WriteSVG(context, w)
w.Header().Set("Content-Type", "image/svg+xml")
saveFile, ok := params.GetString("save_file")
if ok {
sf := createFilename(filename, saveFile)
err = save(planset, sf, logger)
if err != nil {
logger.Errorf("Error during save: %s\n", err.Error())
return
}
}
}