Repository navigation
Expand file tree
/
Copy pathfile_service.go
More file actions
1248 lines (1083 loc) · 33.4 KB
/
Copy pathfile_service.go
File metadata and controls
1248 lines (1083 loc) · 33.4 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 main
import (
"encoding/base64"
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"unicode"
"github.com/civilware/tela"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
// validateFileContent checks file content for issues that would crash the DVM
// Returns a warning string if issues found, empty string if OK
func validateFileContent(data []byte, fileName string) string {
for i, r := range string(data) {
if r > unicode.MaxASCII {
// Find the position for helpful error message
line := 1
col := 1
for j := 0; j < i; j++ {
if data[j] == '\n' {
line++
col = 1
} else {
col++
}
}
return fmt.Sprintf("Non-ASCII character '%c' at line %d, col %d - will fail deployment", r, line, col)
}
}
// Check size
contentSize := float64(len(data)+strings.Count(string(data), "\n")) / 1024
if contentSize > 18 { // MAX_DOC_CODE_SIZE
return fmt.Sprintf("File too large (%.2fKB > 18KB max)", contentSize)
}
return ""
}
// FileService handles file operations
// GetFileInfo returns detailed information about a file
func (a *App) GetFileInfo(filePath string) map[string]interface{} {
a.logToConsole(fmt.Sprintf("[DOC] Getting file info: %s", filePath))
info, err := os.Stat(filePath)
if err != nil {
return map[string]interface{}{
"success": false,
"error": "File not found. Check the path.",
"technicalError": err.Error(),
}
}
// Get absolute path
absPath, _ := filepath.Abs(filePath)
// Detect MIME type
ext := strings.ToLower(filepath.Ext(filePath))
docType := tela.ParseDocType(filepath.Base(filePath))
// Read first few bytes to detect content type
contentPreview := ""
if !info.IsDir() && info.Size() > 0 && info.Size() < 10*1024*1024 { // < 10MB
data, err := os.ReadFile(filePath)
if err == nil && len(data) > 0 {
// Show first 500 bytes as preview for text files
if strings.HasPrefix(docType, "text/") || docType == "application/javascript" || docType == "application/json" {
previewLen := 500
if len(data) < previewLen {
previewLen = len(data)
}
contentPreview = string(data[:previewLen])
}
}
}
return map[string]interface{}{
"success": true,
"name": info.Name(),
"path": absPath,
"size": info.Size(),
"isDir": info.IsDir(),
"modTime": info.ModTime().Unix(),
"extension": ext,
"docType": docType,
"preview": contentPreview,
"canCompress": canCompress(docType),
"gasEstimate": estimateGasCost(int(info.Size())),
}
}
// ShardFile splits a file into DocShards for TELA deployment
func (a *App) ShardFile(filePath string, compress bool) map[string]interface{} {
a.logToConsole(fmt.Sprintf("[File] Sharding file: %s (compress: %v)", filePath, compress))
// Check file exists
info, err := os.Stat(filePath)
if err != nil {
return map[string]interface{}{
"success": false,
"error": "File not found. Check the path.",
"technicalError": err.Error(),
}
}
if info.IsDir() {
return map[string]interface{}{
"success": false,
"error": "Cannot shard a directory",
}
}
// Read file content
data, err := os.ReadFile(filePath)
if err != nil {
return ErrorResponse(err)
}
// tela.CreateShardFiles writes output files into filepath.Dir(filePath) — the
// source file's own directory. Report this as the actual outputDir so the UI
// shows the real location instead of a phantom relative path.
outputDir := filepath.Dir(filePath)
compression := ""
if compress {
compression = tela.COMPRESSION_GZIP
// Compress BEFORE sharding: tela.Compress returns a base64-encoded gzip string.
// If we pass raw data with compression set, CreateShardFiles checks content != nil
// and skips its own compression step — the output would be named .gz but contain
// uncompressed bytes, causing ConstructFromShards to fail with "unexpected EOF"
// when it tries to base64-decode raw content. We compress here so each shard
// file is a fragment of the base64 gzip stream, exactly what ConstructFromShards
// expects when it concatenates and decompresses.
compressed, compErr := tela.Compress(data, compression)
if compErr != nil {
return map[string]interface{}{
"success": false,
"error": "Failed to compress file before sharding",
"technicalError": compErr.Error(),
}
}
data = []byte(compressed)
}
err = tela.CreateShardFiles(filePath, compression, data)
if err != nil {
return ErrorResponse(err)
}
// Count shard files created using the (possibly compressed) data size
totalShards, _ := tela.GetTotalShards(data)
a.logToConsole(fmt.Sprintf("[OK] Created shard files in %s", outputDir))
return map[string]interface{}{
"success": true,
"shardCount": totalShards,
"outputDir": outputDir,
"compressed": compress,
"message": fmt.Sprintf("File sharded into %d parts", totalShards),
}
}
// discoverShardFiles finds DocShard files, parses indices, sorts by index, and returns
// ordered shard bytes plus recreate filename and compression. Matches tela-cli findDocShardFiles behavior.
// entrypointPath can be a directory (we find the first shard set) or a shard file (e.g. file-1.go).
func discoverShardFiles(entrypointPath string) (docShards [][]byte, recreate, compression string, err error) {
info, err := os.Stat(entrypointPath)
if err != nil {
return nil, "", "", err
}
shardDir := entrypointPath
fileName := ""
if !info.IsDir() {
shardDir = filepath.Dir(entrypointPath)
fileName = filepath.Base(entrypointPath)
}
// If directory, find first file matching name-N.ext or name-N.ext.gz
if fileName == "" {
entries, e := os.ReadDir(shardDir)
if e != nil {
return nil, "", "", e
}
for _, e := range entries {
if e.IsDir() {
continue
}
name := e.Name()
base := name
// Strip compression extension first (e.g. .gz), then the original extension
// so that name-1.js.gz correctly yields "name-1" for the numeric check.
if tela.IsCompressedExt(filepath.Ext(base)) {
base = strings.TrimSuffix(base, filepath.Ext(base))
}
base = strings.TrimSuffix(base, filepath.Ext(base))
parts := strings.Split(base, "-")
if len(parts) >= 2 {
if n, pe := strconv.Atoi(parts[len(parts)-1]); pe == nil && n >= 1 {
fileName = name
break
}
}
}
if fileName == "" {
return nil, "", "", fmt.Errorf("no shard files found in %s (expected name-1.ext or name-1.ext.gz)", shardDir)
}
}
split := strings.Split(fileName, "-")
if len(split) < 2 {
return nil, "", "", fmt.Errorf("%q is not a DocShard file", entrypointPath)
}
ext := filepath.Ext(fileName) // used for matching (e.g. .gz for compressed)
prefix := fmt.Sprintf("%s-", split[0])
if tela.IsCompressedExt(ext) {
compression = ext
origExt := filepath.Ext(strings.TrimSuffix(fileName, ext))
recreate = fmt.Sprintf("%s%s", split[0], origExt)
} else {
recreate = fmt.Sprintf("%s%s", split[0], ext)
}
type shardEntry struct {
index int
data []byte
}
var shards []shardEntry
files, err := os.ReadDir(shardDir)
if err != nil {
return nil, "", "", err
}
for _, file := range files {
if file.IsDir() {
continue
}
shardFileName := file.Name()
if !strings.HasPrefix(shardFileName, prefix) || filepath.Ext(shardFileName) != ext {
continue
}
baseName := strings.TrimSuffix(shardFileName, ext)
if compression != "" {
baseName = strings.TrimSuffix(baseName, filepath.Ext(baseName))
}
idxParts := strings.Split(baseName, "-")
if len(idxParts) < 2 {
continue
}
idx, parseErr := strconv.Atoi(idxParts[len(idxParts)-1])
if parseErr != nil {
continue
}
data, errr := os.ReadFile(filepath.Join(shardDir, shardFileName))
if errr != nil {
return nil, "", "", fmt.Errorf("could not read shard file %q: %w", shardFileName, errr)
}
shards = append(shards, shardEntry{index: idx, data: data})
}
if len(shards) == 0 {
return nil, "", "", fmt.Errorf("no shard files found in %s", shardDir)
}
sort.Slice(shards, func(i, j int) bool { return shards[i].index < shards[j].index })
for _, s := range shards {
docShards = append(docShards, s.data)
}
return docShards, recreate, compression, nil
}
// ConstructFromShards reconstructs a file from DocShards
func (a *App) ConstructFromShards(shardPath string) map[string]interface{} {
a.logToConsole(fmt.Sprintf("[Shards] Constructing file from shards: %s", shardPath))
shardFiles, recreate, compression, err := discoverShardFiles(shardPath)
if err != nil {
return map[string]interface{}{
"success": false,
"error": "Failed to discover shard files",
"technicalError": err.Error(),
}
}
shardDir := shardPath
if info, e := os.Stat(shardPath); e == nil && !info.IsDir() {
shardDir = filepath.Dir(shardPath)
}
err = tela.ConstructFromShards(shardFiles, recreate, shardDir, compression)
if err != nil {
return ErrorResponse(err)
}
outputPath := filepath.Join(shardDir, recreate)
outputInfo, _ := os.Stat(outputPath)
size := int64(0)
if outputInfo != nil {
size = outputInfo.Size()
}
a.logToConsole(fmt.Sprintf("[OK] File reconstructed: %s (%d bytes)", outputPath, size))
return map[string]interface{}{
"success": true,
"outputPath": outputPath,
"size": size,
"message": "File reconstructed successfully",
}
}
// DiffFiles compares two files and returns the differences
func (a *App) DiffFiles(file1, file2 string) map[string]interface{} {
a.logToConsole(fmt.Sprintf("[STATS] Diffing files: %s vs %s", file1, file2))
// Read file 1
data1, err := os.ReadFile(file1)
if err != nil {
return ErrorResponse(err)
}
// Read file 2
data2, err := os.ReadFile(file2)
if err != nil {
return ErrorResponse(err)
}
// Split into lines
lines1 := strings.Split(string(data1), "\n")
lines2 := strings.Split(string(data2), "\n")
// Simple line-by-line diff
diffs := computeLineDiff(lines1, lines2)
return map[string]interface{}{
"success": true,
"file1": file1,
"file2": file2,
"file1Lines": len(lines1),
"file2Lines": len(lines2),
"diffs": diffs,
"identical": len(diffs) == 0,
}
}
// DiffSCIDs compares the code of two smart contracts
func (a *App) DiffSCIDs(scid1, scid2 string) map[string]interface{} {
a.logToConsole(fmt.Sprintf("[STATS] Diffing SCIDs: %s vs %s", scid1[:16]+"...", scid2[:16]+"..."))
// Get code for first SCID
result1, err := a.daemonClient.Call("DERO.GetSC", map[string]interface{}{
"scid": scid1,
"code": true,
})
if err != nil {
return map[string]interface{}{
"success": false,
"error": fmt.Sprintf("Failed to get first SC: %v", err),
}
}
// Get code for second SCID
result2, err := a.daemonClient.Call("DERO.GetSC", map[string]interface{}{
"scid": scid2,
"code": true,
})
if err != nil {
return map[string]interface{}{
"success": false,
"error": fmt.Sprintf("Failed to get second SC: %v", err),
}
}
// Extract code strings
code1 := extractCode(result1)
code2 := extractCode(result2)
// Compute diff
lines1 := strings.Split(code1, "\n")
lines2 := strings.Split(code2, "\n")
diffs := computeLineDiff(lines1, lines2)
return map[string]interface{}{
"success": true,
"scid1": scid1,
"scid2": scid2,
"code1Lines": len(lines1),
"code2Lines": len(lines2),
"diffs": diffs,
"identical": len(diffs) == 0,
}
}
// MoveFile moves a file or directory
func (a *App) MoveFile(source, destination string) map[string]interface{} {
a.logToConsole(fmt.Sprintf("[DIR] Moving: %s → %s", source, destination))
// Check source exists
if _, err := os.Stat(source); os.IsNotExist(err) {
return map[string]interface{}{
"success": false,
"error": "Source file not found",
}
}
// Create destination directory if needed
destDir := filepath.Dir(destination)
if err := os.MkdirAll(destDir, 0755); err != nil {
return map[string]interface{}{
"success": false,
"error": fmt.Sprintf("Failed to create destination directory: %v", err),
}
}
// Move the file
if err := os.Rename(source, destination); err != nil {
return map[string]interface{}{
"success": false,
"error": fmt.Sprintf("Failed to move file: %v", err),
}
}
a.logToConsole(fmt.Sprintf("[OK] File moved to: %s", destination))
return map[string]interface{}{
"success": true,
"source": source,
"destination": destination,
"message": "File moved successfully",
}
}
// RemoveFile removes a file or directory (only from datashards/clone)
func (a *App) RemoveFile(path string) map[string]interface{} {
a.logToConsole(fmt.Sprintf("[File] Removing: %s", path))
// Security check: only allow removal from datashards directory
absPath, _ := filepath.Abs(path)
shardsDir, _ := filepath.Abs(filepath.Join(".", "datashards"))
if !strings.HasPrefix(absPath, shardsDir) {
return map[string]interface{}{
"success": false,
"error": "Can only remove files from datashards directory",
}
}
// Check file exists
info, err := os.Stat(path)
if os.IsNotExist(err) {
return map[string]interface{}{
"success": false,
"error": "File not found",
}
}
// Remove file or directory
if info.IsDir() {
if err := os.RemoveAll(path); err != nil {
return map[string]interface{}{
"success": false,
"error": fmt.Sprintf("Failed to remove directory: %v", err),
}
}
} else {
if err := os.Remove(path); err != nil {
return map[string]interface{}{
"success": false,
"error": fmt.Sprintf("Failed to remove file: %v", err),
}
}
}
a.logToConsole(fmt.Sprintf("[OK] Removed: %s", path))
return map[string]interface{}{
"success": true,
"path": path,
"message": "File removed successfully",
}
}
// ListDirectory lists contents of a directory
func (a *App) ListDirectory(dirPath string) map[string]interface{} {
entries, err := os.ReadDir(dirPath)
if err != nil {
return map[string]interface{}{
"success": false,
"error": fmt.Sprintf("Failed to read directory: %v", err),
}
}
items := []map[string]interface{}{}
for _, entry := range entries {
info, _ := entry.Info()
items = append(items, map[string]interface{}{
"name": entry.Name(),
"isDir": entry.IsDir(),
"size": info.Size(),
"modTime": info.ModTime().Unix(),
})
}
return map[string]interface{}{
"success": true,
"path": dirPath,
"items": items,
"count": len(items),
}
}
// ================== FOLDER SELECTION ==================
// SelectFolder opens a native directory picker dialog
func (a *App) SelectFolder() string {
selection, err := runtime.OpenDirectoryDialog(a.ctx, runtime.OpenDialogOptions{
Title: "Select Folder for TELA Deployment",
CanCreateDirectories: false,
})
if err != nil {
log.Printf("Error opening directory dialog: %v", err)
return ""
}
return selection
}
// SelectFile opens a native file picker dialog
func (a *App) SelectFile() string {
selection, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{
Title: "Select File",
})
if err != nil {
log.Printf("Error opening file dialog: %v", err)
return ""
}
return selection
}
// ReadTextFile reads a text file and returns its content.
// Used by the Deploy SC flow to load .bas files from disk.
func (a *App) ReadTextFile(filePath string) map[string]interface{} {
if filePath == "" {
return map[string]interface{}{
"success": false,
"error": "No file path provided",
}
}
info, err := os.Stat(filePath)
if err != nil {
return map[string]interface{}{
"success": false,
"error": "File not found: " + err.Error(),
}
}
const maxSize = 1 * 1024 * 1024 // 1MB
if info.Size() > maxSize {
return map[string]interface{}{
"success": false,
"error": fmt.Sprintf("File too large (%d bytes). Maximum is 1MB.", info.Size()),
}
}
data, err := os.ReadFile(filePath)
if err != nil {
return map[string]interface{}{
"success": false,
"error": "Failed to read file: " + err.Error(),
}
}
return map[string]interface{}{
"success": true,
"content": string(data),
"size": len(data),
"filename": info.Name(),
}
}
// SelectFiles opens a native multiple file picker dialog for TELA DOC uploads
func (a *App) SelectFiles() map[string]interface{} {
a.logToConsole("[FILE] SelectFiles: Opening native file dialog...")
selections, err := runtime.OpenMultipleFilesDialog(a.ctx, runtime.OpenDialogOptions{
Title: "Select Files for TELA Upload",
Filters: []runtime.FileFilter{
{
DisplayName: "Web Files",
Pattern: "*.html;*.htm;*.css;*.js;*.json;*.svg;*.png;*.jpg;*.jpeg;*.gif;*.webp;*.ico;*.woff;*.woff2;*.ttf",
},
{
DisplayName: "All Files",
Pattern: "*.*",
},
},
})
if err != nil {
a.logToConsole(fmt.Sprintf("[ERR] SelectFiles: Dialog error - %v", err))
return map[string]interface{}{
"success": false,
"error": err.Error(),
}
}
a.logToConsole(fmt.Sprintf("[FILE] SelectFiles: Dialog returned %d selections", len(selections)))
if len(selections) == 0 {
a.logToConsole("[FILE] SelectFiles: No files selected (user cancelled)")
return map[string]interface{}{
"success": false,
"error": "No files selected",
}
}
// Process selected files
a.logToConsole("[FILE] SelectFiles: Processing selected files...")
var files []map[string]interface{}
for _, filePath := range selections {
info, err := os.Stat(filePath)
if err != nil {
a.logToConsole(fmt.Sprintf("[WARN] SelectFiles: Could not stat %s - %v", filePath, err))
continue
}
// Read file content
content, err := os.ReadFile(filePath)
if err != nil {
a.logToConsole(fmt.Sprintf("[WARN] SelectFiles: Could not read %s - %v", filePath, err))
continue
}
files = append(files, map[string]interface{}{
"name": info.Name(),
"path": filePath,
"subDir": "/",
"size": info.Size(),
"type": detectMimeType(info.Name()),
"data": string(content),
})
a.logToConsole(fmt.Sprintf("[FILE] SelectFiles: Loaded %s (%d bytes)", info.Name(), info.Size()))
}
a.logToConsole(fmt.Sprintf("[OK] SelectFiles: Returning %d files", len(files)))
return map[string]interface{}{
"success": true,
"files": files,
}
}
// detectMimeType returns the MIME type based on file extension
func detectMimeType(filename string) string {
ext := strings.ToLower(filepath.Ext(filename))
mimeTypes := map[string]string{
".html": "text/html",
".htm": "text/html",
".css": "text/css",
".js": "application/javascript",
".json": "application/json",
".svg": "image/svg+xml",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".webp": "image/webp",
".woff": "font/woff",
".woff2": "font/woff2",
".ttf": "font/ttf",
".ico": "image/x-icon",
}
if mime, ok := mimeTypes[ext]; ok {
return mime
}
return "application/octet-stream"
}
// ================== BATCH UPLOAD (Folder Scanner) ==================
// FolderScanResult represents the result of scanning a folder
type FolderScanResult struct {
Files []ScannedFile `json:"files"`
TotalFiles int `json:"totalFiles"`
TotalSize int64 `json:"totalSize"`
TotalGas uint64 `json:"totalGas"`
FolderPath string `json:"folderPath"`
Errors []string `json:"errors"`
}
// ScannedFile represents a file found during folder scanning
type ScannedFile struct {
Name string `json:"name"`
Path string `json:"path"`
RelPath string `json:"relPath"`
SubDir string `json:"subDir"`
DocType string `json:"docType"`
Size int64 `json:"size"`
IsEntryPoint bool `json:"isEntryPoint"` // e.g., index.html
CanCompress bool `json:"canCompress"`
GasEstimate uint64 `json:"gasEstimate"`
ValidationWarn string `json:"validationWarn,omitempty"` // Warning about content issues
}
// ScanFolder recursively scans a folder for TELA deployment
func (a *App) ScanFolder(folderPath string) map[string]interface{} {
a.logToConsole(fmt.Sprintf("[DIR] Scanning folder for TELA deployment: %s", folderPath))
// Validate folder exists
info, err := os.Stat(folderPath)
if err != nil {
return map[string]interface{}{
"success": false,
"error": fmt.Sprintf("Folder not found: %v", err),
}
}
if !info.IsDir() {
return map[string]interface{}{
"success": false,
"error": "Path is not a directory",
}
}
result := FolderScanResult{
Files: []ScannedFile{},
FolderPath: folderPath,
Errors: []string{},
}
// Walk the folder
err = filepath.Walk(folderPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
result.Errors = append(result.Errors, fmt.Sprintf("Error accessing %s: %v", path, err))
return nil // Continue walking
}
// Skip directories
if info.IsDir() {
return nil
}
// Skip hidden files and common exclusions
name := info.Name()
if strings.HasPrefix(name, ".") || name == "Thumbs.db" || name == ".DS_Store" {
return nil
}
// Calculate relative path and subDir
relPath, _ := filepath.Rel(folderPath, path)
subDir := filepath.Dir(relPath)
if subDir == "." {
subDir = "/"
} else {
subDir = "/" + filepath.ToSlash(subDir)
}
// Detect document type
docType := tela.ParseDocType(name)
// Check if this is an entry point
isEntry := strings.ToLower(name) == "index.html" && (subDir == "/" || subDir == "")
// Validate content for DVM compatibility (read file to check)
var validationWarn string
if data, readErr := os.ReadFile(path); readErr == nil {
validationWarn = validateFileContent(data, name)
if validationWarn != "" {
result.Errors = append(result.Errors, fmt.Sprintf("%s: %s", name, validationWarn))
}
}
file := ScannedFile{
Name: name,
Path: path,
RelPath: relPath,
SubDir: subDir,
DocType: docType,
Size: info.Size(),
IsEntryPoint: isEntry,
CanCompress: canCompress(docType),
GasEstimate: estimateGasCost(int(info.Size())),
ValidationWarn: validationWarn,
}
result.Files = append(result.Files, file)
result.TotalSize += info.Size()
result.TotalGas += file.GasEstimate
return nil
})
if err != nil {
result.Errors = append(result.Errors, fmt.Sprintf("Walk error: %v", err))
}
result.TotalFiles = len(result.Files)
a.logToConsole(fmt.Sprintf("[OK] Scanned %d files (%.2f KB, ~%d gas)",
result.TotalFiles,
float64(result.TotalSize)/1024,
result.TotalGas))
return map[string]interface{}{
"success": true,
"files": result.Files,
"totalFiles": result.TotalFiles,
"totalSize": result.TotalSize,
"totalGas": result.TotalGas,
"folderPath": result.FolderPath,
"errors": result.Errors,
}
}
// PreflightExpand scans a folder and returns an expanded deploy plan.
// When config.AutoShard is true, files exceeding the DOC size limit are split
// in-memory into shard DOCInfos. No files are written to disk.
//
// This endpoint is called by BatchUpload.svelte when the auto-shard toggle is on.
// It does NOT replace or modify ScanFolder — that path remains unchanged.
//
// configJSON must be a JSON string matching PreflightConfig:
// {"autoShard": true, "compress": true, "indexDurl": "my-app.tela"}
func (a *App) PreflightExpand(folderPath, configJSON string) map[string]interface{} {
a.logToConsole(fmt.Sprintf("[DIR] PreflightExpand: scanning %s", folderPath))
var config PreflightConfig
if err := json.Unmarshal([]byte(configJSON), &config); err != nil {
return map[string]interface{}{"success": false, "error": "Invalid config JSON: " + err.Error()}
}
// Validate folder exists
info, err := os.Stat(folderPath)
if err != nil {
return map[string]interface{}{"success": false, "error": fmt.Sprintf("Folder not found: %v", err)}
}
if !info.IsDir() {
return map[string]interface{}{"success": false, "error": "Path is not a directory"}
}
// Walk the folder and build DOCInfo slice — same filtering logic as ScanFolder.
var files []DOCInfo
var scanErrors []string
err = filepath.Walk(folderPath, func(path string, fi os.FileInfo, walkErr error) error {
if walkErr != nil {
scanErrors = append(scanErrors, fmt.Sprintf("Error accessing %s: %v", path, walkErr))
return nil
}
if fi.IsDir() {
return nil
}
name := fi.Name()
// Skip hidden files, build artifacts, and shard output directories
if strings.HasPrefix(name, ".") || name == "Thumbs.db" || name == ".DS_Store" {
return nil
}
// Skip hidden directories (e.g. .git, .doc-shards)
rel, _ := filepath.Rel(folderPath, path)
for _, part := range strings.Split(filepath.ToSlash(rel), "/") {
if strings.HasPrefix(part, ".") {
return nil
}
}
relPath, _ := filepath.Rel(folderPath, path)
subDir := filepath.Dir(relPath)
if subDir == "." {
subDir = "/"
} else {
subDir = "/" + filepath.ToSlash(subDir)
}
docType := tela.ParseDocType(name)
files = append(files, DOCInfo{
Name: name,
Path: path,
SubDir: subDir,
DocType: docType,
Size: fi.Size(),
})
return nil
})
if err != nil {
scanErrors = append(scanErrors, fmt.Sprintf("Walk error: %v", err))
}
if len(files) == 0 {
return map[string]interface{}{
"success": false,
"error": "No deployable files found in folder",
"errors": scanErrors,
}
}
expansion, err := a.buildPreflightExpansion(files, config)
if err != nil {
return map[string]interface{}{"success": false, "error": err.Error(), "errors": scanErrors}
}
a.logToConsole(fmt.Sprintf("[OK] PreflightExpand: %d source files → %d deploy DOCs (%d shards, ~%d gas)",
expansion.Summary.SourceFileCount,
expansion.Summary.DeployDocCount,
expansion.Summary.ShardCount,
expansion.Summary.EstimatedGas,
))
return map[string]interface{}{
"success": true,
"deployFiles": expansion.DeployFiles,
"shardGroups": expansion.ShardGroups,
"warnings": expansion.Warnings,
"summary": expansion.Summary,
"errors": scanErrors,
}
}
// GenerateSubDirs generates subDir paths from a list of files
func (a *App) GenerateSubDirs(folderPath string, filesJSON string) map[string]interface{} {
// Parse files array
var files []map[string]interface{}
if err := json.Unmarshal([]byte(filesJSON), &files); err != nil {
return map[string]interface{}{
"success": false,
"error": "Invalid files JSON",
}
}
// Generate subDirs
result := []map[string]interface{}{}
for _, f := range files {
path, ok := f["path"].(string)
if !ok {
continue
}
relPath, _ := filepath.Rel(folderPath, path)
subDir := filepath.Dir(relPath)
if subDir == "." {
subDir = "/"
} else {
subDir = "/" + filepath.ToSlash(subDir)
}
f["subDir"] = subDir
result = append(result, f)
}
return map[string]interface{}{
"success": true,
"files": result,
}
}
// DetectDocTypes updates doc types for a list of files
func (a *App) DetectDocTypes(filesJSON string) map[string]interface{} {
var files []map[string]interface{}
if err := json.Unmarshal([]byte(filesJSON), &files); err != nil {
return map[string]interface{}{
"success": false,
"error": "Invalid files JSON",
}
}
for i := range files {
if name, ok := files[i]["name"].(string); ok {
files[i]["docType"] = tela.ParseDocType(name)
}
}
return map[string]interface{}{
"success": true,
"files": files,
}
}
// EstimateBatchGas calculates total gas for a batch of files
func (a *App) EstimateBatchGas(filesJSON string) map[string]interface{} {
var files []map[string]interface{}
if err := json.Unmarshal([]byte(filesJSON), &files); err != nil {
return map[string]interface{}{
"success": false,
"error": "Invalid files JSON",
}
}
var totalGas uint64