Repository navigation
Expand file tree
/
Copy pathapp.go
More file actions
1607 lines (1373 loc) · 50.1 KB
/
Copy pathapp.go
File metadata and controls
1607 lines (1373 loc) · 50.1 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
// Copyright 2026-present raml-dev
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"context"
"crypto/sha1"
_ "embed"
"encoding/json"
"errors"
"fmt"
"log/slog"
"os"
"path/filepath"
"solo/internal/appinfo"
"solo/internal/auth"
"solo/internal/collection"
"solo/internal/configuration"
"solo/internal/environment"
"solo/internal/exporter"
"solo/internal/fonts"
"solo/internal/git"
"solo/internal/host"
"solo/internal/importer"
"solo/internal/requester"
"solo/internal/runner"
"solo/internal/script"
"solo/internal/theme"
"solo/internal/tools"
"solo/internal/troubleshooting"
"strings"
"sync"
"time"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
//go:embed wails.json
var wailsJSON []byte
// App struct
type App struct {
ctx context.Context
service *requester.Service
collectionManager *collection.CollectionManager
environmentManager *environment.EnvironmentManager
configManager *configuration.ConfigurationManager
hostManager *host.HostManager
scriptManager *script.ScriptManager
authManager *auth.AuthManager
runner *runner.Runner
gitManager *git.Manager
cancelFuncs map[string]context.CancelFunc
cancelMu sync.Mutex
runnerCancel context.CancelFunc
runnerMu sync.Mutex
}
func (a *App) emitEvent(eventName string, data ...interface{}) {
if a.ctx == nil {
return
}
defer func() {
if r := recover(); r != nil {
slog.Debug("Skipping event emit: invalid Wails context", "event", eventName, "recover", r)
}
}()
runtime.EventsEmit(a.ctx, eventName, data...)
}
type RequestOptions struct {
RequestID string `json:"requestId"`
Method string `json:"method"`
URL string `json:"url"`
Headers map[string]any `json:"headers"`
Body string `json:"body"`
CollectionName string `json:"collectionName,omitempty"`
Auth *collection.AuthConfiguration `json:"auth,omitempty"`
Settings *configuration.RequestSettingsOverride `json:"settings,omitempty"`
PreRequestScript string `json:"preRequestScript,omitempty"`
PostResponseScript string `json:"postResponseScript,omitempty"`
}
func (a *App) GetAppInfo() appinfo.AppInfo {
return appinfo.GetAppInfo(wailsJSON)
}
// GetUpdatesFromRepo fetches release updates and emits an event for the frontend.
func (a *App) GetUpdatesFromRepo() (*appinfo.GitHubResponse, error) {
dc := appinfo.InitDiscoveryClient(a.GetAppInfo().GHLink)
includePrereleases := false
if a.configManager != nil {
includePrereleases = a.configManager.Get().General.IncludePrereleaseUpdates
}
info, err := dc.GetUpdatesFromRepo(a.GetAppInfo().ProductVersion, includePrereleases)
if err != nil {
a.emitEvent("updates:error", err.Error())
return nil, err
}
if info != nil && info.Release != nil {
a.emitEvent("updates:available", info)
}
return info, nil
}
// RunParallel performs parallel HTTP requests for load testing.
func (a *App) RunParallel(options RequestOptions, concurrency, iterations int, stopOnError bool) (runner.RunnerStats, error) {
if a.runner == nil {
return runner.RunnerStats{}, fmt.Errorf("runner not initialized")
}
ctx, cancel := context.WithCancel(a.ctx)
a.runnerMu.Lock()
if a.runnerCancel != nil {
a.runnerCancel()
}
a.runnerCancel = cancel
a.runnerMu.Unlock()
defer func() {
a.runnerMu.Lock()
a.runnerCancel = nil
a.runnerMu.Unlock()
cancel()
}()
execOpts := requester.ExecutionOptions{
Method: options.Method,
URL: options.URL,
Body: options.Body,
Headers: options.Headers,
Cookies: nil,
CollectionVariables: a.loadCollectionVariableValues(options.CollectionName),
Auth: options.Auth,
Settings: options.Settings,
PreRequestScript: options.PreRequestScript,
PostResponseScript: options.PostResponseScript,
}
opts := runner.RunnerOptions{
Concurrency: concurrency,
Iterations: iterations,
StopOnError: stopOnError,
Request: execOpts,
}
onResult := func(res runner.RunnerResult) {
a.emitEvent("runner:result", res)
}
return a.runner.Run(ctx, opts, onResult), nil
}
// CancelRunner stops an in-progress RunParallel execution.
func (a *App) CancelRunner() {
a.runnerMu.Lock()
defer a.runnerMu.Unlock()
if a.runnerCancel != nil {
a.runnerCancel()
}
}
// dummy function to emit RunnerResult
func (a *App) GetRunnerResult() runner.RunnerResult {
return runner.RunnerResult{}
}
// NewApp creates a new App application struct
func NewApp() *App {
cm, err := configuration.NewConfigurationManager()
if err != nil {
slog.Warn("FATAL: Failed to initialize configuration manager", "error", err)
}
configDir, _ := tools.GetOrCreateConfigDir()
am := auth.NewAuthManager(configDir)
hm := host.NewHostManager()
em := environment.NewEnvironmentManager(cm)
// ScriptManager is created without context here; context is set in startup()
sm := script.NewScriptManager(context.TODO())
service := requester.NewService(cm, em, sm, hm, am)
return &App{
service: service,
collectionManager: collection.NewCollectionManager(am),
environmentManager: em,
configManager: cm,
hostManager: hm,
scriptManager: sm,
authManager: am,
runner: runner.NewRunner(service),
gitManager: git.NewManager(),
cancelFuncs: make(map[string]context.CancelFunc),
}
}
// RevealBearerToken returns a locally stored bearer token after an explicit UI action.
func (a *App) RevealBearerToken(tokenID string) (string, error) {
if a.authManager == nil {
return "", fmt.Errorf("auth manager not initialized")
}
return a.authManager.GetBearerToken(tokenID)
}
// startup is called when the app starts. The context is saved
// so we can call the runtime methods.
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
// Inject the real Wails context into ScriptManager so env.set() can emit events
if a.scriptManager != nil {
a.scriptManager.SetContext(ctx)
}
if a.authManager != nil {
a.authManager.SetContext(ctx)
}
if a.service != nil {
a.service.SetContext(ctx)
}
debugMode := false
if a.configManager != nil {
cfg := a.configManager.Get()
debugMode = cfg.General.DebugMode
a.SetDebugMode(cfg.General.DebugMode)
}
slog.Info("Application started", "debug_mode", debugMode)
}
func (a *App) ForceQuit() {
if a.ctx != nil {
runtime.Quit(a.ctx)
}
}
// Execute performs the HTTP request with the given options.
func (a *App) Execute(options RequestOptions) (*requester.ResponseData, error) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if options.RequestID != "" {
a.cancelMu.Lock()
// If there is already a cancel func for this ID, cancel it
if oldCancel, exists := a.cancelFuncs[options.RequestID]; exists {
oldCancel()
}
a.cancelFuncs[options.RequestID] = cancel
a.cancelMu.Unlock()
defer func() {
a.cancelMu.Lock()
delete(a.cancelFuncs, options.RequestID)
a.cancelMu.Unlock()
}()
}
execOpts := requester.ExecutionOptions{
Method: options.Method,
URL: options.URL,
Body: options.Body,
Headers: options.Headers,
Cookies: nil,
CollectionVariables: a.loadCollectionVariableValues(options.CollectionName),
Auth: options.Auth,
Settings: options.Settings,
PreRequestScript: options.PreRequestScript,
PostResponseScript: options.PostResponseScript,
}
resp, err := a.service.ExecuteRequest(ctx, execOpts)
if err != nil && errors.Is(err, context.Canceled) {
slog.Info("Request cancelled by user", "requestId", options.RequestID)
}
return resp, err
}
// CancelExecute cancels an ongoing request execution.
func (a *App) CancelExecute(requestID string) {
a.cancelMu.Lock()
defer a.cancelMu.Unlock()
if cancel, exists := a.cancelFuncs[requestID]; exists {
cancel()
delete(a.cancelFuncs, requestID)
slog.Info("Sent cancel signal to request", "requestId", requestID)
}
}
// GetSessionVars returns the current in-memory session variables set by scripts.
func (a *App) GetSessionVars() map[string]string {
if a.scriptManager == nil {
return map[string]string{}
}
return a.scriptManager.GetSessionVars()
}
// RemoveSessionVar removes a single session variable set by scripts.
func (a *App) RemoveSessionVar(key string) {
if a.scriptManager != nil {
a.scriptManager.RemoveSessionVar(key)
}
}
// ClearSessionVars clears all session variables set by scripts.
func (a *App) ClearSessionVars() {
if a.scriptManager != nil {
a.scriptManager.ClearSessionVars()
}
}
// Theme Management Methods (now routed to ConfigManager)
// GetActiveTheme returns the name of the currently active theme.
func (a *App) GetActiveTheme() string {
if a.configManager == nil {
return "default-light"
}
return a.configManager.GetActiveTheme()
}
// SetActiveTheme sets the active theme by name and persists the change.
func (a *App) SetActiveTheme(themeName string) error {
if a.configManager == nil {
return fmt.Errorf("configuration manager not initialized")
}
return a.configManager.SetActiveTheme(themeName)
}
// GetCustomThemes returns all user-created themes.
func (a *App) GetCustomThemes() []theme.Theme {
if a.configManager == nil {
return []theme.Theme{}
}
return a.configManager.GetCustomThemes()
}
// GetAllThemes returns all available themes, both predefined and custom.
func (a *App) GetAllThemes() []theme.Theme {
if a.configManager == nil {
return []theme.Theme{}
}
return a.configManager.GetAllThemes()
}
// SaveCustomTheme saves a new theme or updates an existing one.
func (a *App) SaveCustomTheme(theme theme.Theme) error {
if a.configManager == nil {
return fmt.Errorf("configuration manager not initialized")
}
return a.configManager.SaveCustomTheme(theme)
}
// DeleteCustomTheme removes a custom theme by name.
func (a *App) DeleteCustomTheme(themeName string) error {
if a.configManager == nil {
return fmt.Errorf("configuration manager not initialized")
}
return a.configManager.DeleteCustomTheme(themeName)
}
// GetThemeByName finds and returns a single theme (predefined or custom) by its name.
func (a *App) GetThemeByName(themeName string) (*theme.Theme, error) {
if a.configManager == nil {
return nil, fmt.Errorf("configuration manager not initialized")
}
return a.configManager.GetThemeByName(themeName)
}
// Font Management Methods
// SetDefaultFontFamily sets the default font family and persists the change.
func (a *App) SetDefaultFontFamily(fontFamily string) error {
if a.configManager == nil {
return fmt.Errorf("configuration manager not initialized")
}
return a.configManager.SetDefaultFontFamily(fontFamily)
}
// SetMonoFontFamily sets the monospace font family and persists the change.
func (a *App) SetMonoFontFamily(fontFamily string) error {
if a.configManager == nil {
return fmt.Errorf("configuration manager not initialized")
}
return a.configManager.SetMonoFontFamily(fontFamily)
}
// SetZoomLevel updates and persists the UI zoom level.
func (a *App) SetZoomLevel(level float64) error {
if a.configManager == nil {
return fmt.Errorf("configuration manager not initialized")
}
return a.configManager.SetZoomLevel(level)
}
// Host Management Methods
// GetAllHosts returns a list of all configured hosts.
func (a *App) GetAllHosts() ([]host.Host, error) {
if a.hostManager == nil {
return nil, fmt.Errorf("host manager not initialized")
}
return a.hostManager.GetAllHosts(), nil
}
// UpsertHost creates a new host configuration or updates an existing one.
func (a *App) UpsertHost(h host.Host) error {
if a.hostManager == nil {
return fmt.Errorf("host manager not initialized")
}
return a.hostManager.UpsertHost(h)
}
// DeleteHost removes a host configuration by its name (hostname).
func (a *App) DeleteHost(hostname string) error {
if a.hostManager == nil {
return fmt.Errorf("host manager not initialized")
}
return a.hostManager.DeleteHost(hostname)
}
// GetSelectedEnvironment returns the persisted selected environment name
func (a *App) GetSelectedEnvironment() string {
if a.configManager == nil {
return ""
}
return a.configManager.GetSelectedEnvironment()
}
// SetSelectedEnvironment persists the selected environment name
func (a *App) SetSelectedEnvironment(name string) error {
if a.configManager == nil {
return fmt.Errorf("configuration manager not initialized")
}
return a.configManager.SetSelectedEnvironment(name)
}
// Collection Management Methods
// ImportPostmanCollections imports Postman v2.1 collection files into Solo.
func (a *App) ImportPostmanCollections(paths []string, overwriteExisting bool) (collection.BatchImportResult, error) {
if a.collectionManager == nil {
return collection.BatchImportResult{}, fmt.Errorf("collection manager not initialized")
}
imp := importer.NewPostmanImporter()
return a.collectionManager.ImportBatch(paths, overwriteExisting, func(path string) (*collection.Collection, []string, error) {
coll, err := imp.Import(path)
return coll, nil, err
})
}
// ImportOpenAPICollections imports OpenAPI 3.x or Swagger 2.x collection files into Solo.
func (a *App) ImportOpenAPICollections(paths []string, overwriteExisting bool) (collection.BatchImportResult, error) {
if a.collectionManager == nil {
return collection.BatchImportResult{}, fmt.Errorf("collection manager not initialized")
}
imp := importer.NewOpenAPIImporter()
return a.collectionManager.ImportBatch(paths, overwriteExisting, func(path string) (*collection.Collection, []string, error) {
result, err := imp.Import(path)
if err != nil {
return nil, nil, err
}
return result.Collection, result.Warnings, nil
})
}
// ImportCurlRequest parses a cURL command string and adds the resulting request
// to the specified collection.
func (a *App) ImportCurlRequest(curlString, collectionName string) error {
imp := importer.NewCurlImporter()
req, err := imp.ParseRequest(curlString)
if err != nil {
return fmt.Errorf("failed to parse cURL command: %w", err)
}
if _, err := a.collectionManager.AddRequest(collectionName, req); err != nil {
return fmt.Errorf("failed to add request to collection %q: %w", collectionName, err)
}
return nil
}
// ExportCollection opens a native save dialog and writes the collection as Solo-native JSON.
func (a *App) ExportCollection(collectionName string) error {
coll, err := a.collectionManager.LoadCollection(collectionName)
if err != nil {
return fmt.Errorf("failed to load collection %q: %w", collectionName, err)
}
path, err := runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{
Title: "Export Collection",
DefaultFilename: collectionName + ".json",
Filters: []runtime.FileFilter{
{DisplayName: "JSON files", Pattern: "*.json"},
},
})
if err != nil {
return fmt.Errorf("save dialog error: %w", err)
}
if path == "" {
return nil // user cancelled
}
data, err := json.MarshalIndent(coll, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal collection: %w", err)
}
return os.WriteFile(path, data, 0644)
}
// ExportOpenAPICollection opens a native save dialog and writes the collection as an OpenAPI 3.1 YAML document.
func (a *App) ExportOpenAPICollection(collectionName string) error {
coll, err := a.collectionManager.LoadCollection(collectionName)
if err != nil {
return fmt.Errorf("failed to load collection %q: %w", collectionName, err)
}
path, err := runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{
Title: "Export as OpenAPI",
DefaultFilename: collectionName + ".yaml",
Filters: []runtime.FileFilter{
{DisplayName: "YAML files", Pattern: "*.yaml"},
},
})
if err != nil {
return fmt.Errorf("save dialog error: %w", err)
}
if path == "" {
return nil // user cancelled
}
data, err := exporter.ExportOpenAPI(coll)
if err != nil {
return fmt.Errorf("failed to export collection as OpenAPI: %w", err)
}
return os.WriteFile(path, data, 0644)
}
// ExportEnvironment opens a native save dialog and writes the environment as Solo-native JSON.
func (a *App) ExportEnvironment(environmentName string) error {
env, err := a.environmentManager.LoadEnvironment(environmentName)
if err != nil {
return fmt.Errorf("failed to load environment %q: %w", environmentName, err)
}
path, err := runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{
Title: "Export Environment",
DefaultFilename: environmentName + ".json",
Filters: []runtime.FileFilter{
{DisplayName: "JSON files", Pattern: "*.json"},
},
})
if err != nil {
return fmt.Errorf("save dialog error: %w", err)
}
if path == "" {
return nil // user cancelled
}
data, err := json.MarshalIndent(env, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal environment: %w", err)
}
return os.WriteFile(path, data, 0644)
}
func (a *App) loadSoloCollectionForImport(path string) (*collection.Collection, []string, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, nil, fmt.Errorf("failed to read file: %w", err)
}
var coll collection.Collection
if err := json.Unmarshal(data, &coll); err != nil {
return nil, nil, fmt.Errorf("invalid %s collection file: %w", tools.APP_NAME, err)
}
if coll.Name == "" {
return nil, nil, fmt.Errorf("collection file has no name field")
}
return &coll, nil, nil
}
// ImportSoloCollections imports Solo-native collection JSON files into Solo.
func (a *App) ImportSoloCollections(paths []string, overwriteExisting bool) (collection.BatchImportResult, error) {
if a.collectionManager == nil {
return collection.BatchImportResult{}, fmt.Errorf("collection manager not initialized")
}
importOne := func(path string) (*collection.Collection, []string, error) {
return a.loadSoloCollectionForImport(path)
}
return a.collectionManager.ImportBatch(paths, overwriteExisting, importOne)
}
// ImportSoloEnvironment imports a Solo-native environment JSON file.
// If overwrite is false and an environment with the same name already exists,
// returns an error of the form "environment <name> already exists".
func (a *App) ImportSoloEnvironment(path string, overwrite bool) error {
data, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("failed to read file: %w", err)
}
var env environment.Environment
if err := json.Unmarshal(data, &env); err != nil {
return fmt.Errorf("invalid %s environment file: %w", tools.APP_NAME, err)
}
if env.Name == "" {
return fmt.Errorf("environment file has no name field")
}
if !overwrite {
existing, _ := a.environmentManager.LoadEnvironment(env.Name)
if existing != nil {
return fmt.Errorf("environment %s already exists", env.Name)
}
}
if err := a.environmentManager.UpdateEnvironment(&env); err != nil {
return fmt.Errorf("failed to save environment: %w", err)
}
return nil
}
// GenerateCurl converts a resolved HTTP request into a multi-line cURL command string.
func (a *App) GenerateCurl(req exporter.CurlExportRequest) (string, error) {
return exporter.GenerateCurl(req), nil
}
// SaveCurlFile opens a native save dialog and writes the cURL string to the chosen path.
func (a *App) SaveCurlFile(content, suggestedName string) error {
path, err := runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{
Title: "Save cURL command",
DefaultFilename: suggestedName,
Filters: []runtime.FileFilter{
{DisplayName: "Shell scripts", Pattern: "*.sh"},
},
})
if err != nil {
return fmt.Errorf("save dialog error: %w", err)
}
if path == "" {
return nil // user cancelled
}
return os.WriteFile(path, []byte(content), 0644)
}
// SaveHarFile opens a native save dialog and writes the HAR content to the chosen path.
func (a *App) SaveHarFile(content, suggestedName string) error {
path, err := runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{
Title: "Export HAR",
DefaultFilename: suggestedName,
Filters: []runtime.FileFilter{
{DisplayName: "HAR files", Pattern: "*.har"},
},
})
if err != nil {
return fmt.Errorf("save dialog error: %w", err)
}
if path == "" {
return nil // user cancelled
}
return os.WriteFile(path, []byte(content), 0644)
}
// ExportLogsZip creates a ZIP archive with all files in the app logs directory
// (including rotated/compressed ones) and saves it via native save dialog.
func (a *App) ExportLogsZip() (bool, error) {
configRoot, err := tools.GetOrCreateConfigDir()
if err != nil {
return false, fmt.Errorf("failed to resolve config directory: %w", err)
}
logsDir := filepath.Join(configRoot, "logs")
zipBytes, includedFiles, err := troubleshooting.BuildLogsZip(logsDir)
if err != nil {
if errors.Is(err, troubleshooting.ErrNoLogFiles) || errors.Is(err, os.ErrNotExist) {
return false, fmt.Errorf("no log files found to export")
}
return false, fmt.Errorf("failed to build logs archive: %w", err)
}
defaultFilename := fmt.Sprintf("%s-logs-%s.zip", tools.APP_NAME, time.Now().Format("20060102-150405"))
path, err := runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{
Title: "Export Logs",
DefaultFilename: defaultFilename,
Filters: []runtime.FileFilter{
{DisplayName: "ZIP archives", Pattern: "*.zip"},
},
})
if err != nil {
return false, fmt.Errorf("save dialog error: %w", err)
}
if path == "" {
return false, nil // user cancelled
}
if err := os.WriteFile(path, zipBytes, 0644); err != nil {
return false, fmt.Errorf("failed to write archive: %w", err)
}
slog.Info("Logs archive exported", "path", path, "files", len(includedFiles))
return true, nil
}
// ImportBrunoCollections imports Bruno collection directories into Solo.
func (a *App) ImportBrunoCollections(paths []string, overwriteExisting bool) (collection.BatchImportResult, error) {
if a.collectionManager == nil {
return collection.BatchImportResult{}, fmt.Errorf("collection manager not initialized")
}
imp := importer.NewBrunoImporter()
return a.collectionManager.ImportBatch(paths, overwriteExisting, func(path string) (*collection.Collection, []string, error) {
coll, err := imp.Import(path)
return coll, nil, err
})
}
// ImportPostmanEnvironment imports a Postman environment JSON file.
func (a *App) ImportPostmanEnvironment(path string, overwrite bool) error {
imp := importer.NewPostmanEnvironmentImporter()
env, err := imp.Import(path)
if err != nil {
return fmt.Errorf("failed to import Postman environment: %w", err)
}
if a.environmentManager != nil {
existing, loadErr := a.environmentManager.LoadEnvironment(env.Name)
if loadErr == nil && existing != nil && !overwrite {
return fmt.Errorf("environment %s already exists", env.Name)
}
}
if err := a.environmentManager.UpdateEnvironment(env); err != nil {
return fmt.Errorf("failed to save imported environment: %w", err)
}
return nil
}
// ImportBrunoEnvironment imports a Bruno environment .bru file.
func (a *App) ImportBrunoEnvironment(path string, overwrite bool) error {
imp := importer.NewBrunoEnvironmentImporter()
env, err := imp.Import(path)
if err != nil {
return fmt.Errorf("failed to import Bruno environment: %w", err)
}
if a.environmentManager != nil {
existing, loadErr := a.environmentManager.LoadEnvironment(env.Name)
if loadErr == nil && existing != nil && !overwrite {
return fmt.Errorf("environment %s already exists", env.Name)
}
}
if err := a.environmentManager.UpdateEnvironment(env); err != nil {
return fmt.Errorf("failed to save imported environment: %w", err)
}
return nil
}
// CreateCollection creates a new, empty collection.
func (a *App) CreateCollection(collectionName string) error {
return a.collectionManager.CreateCollection(collectionName)
}
// LoadCollections returns a list of all available collection names.
func (a *App) LoadCollections() (*[]string, error) {
return a.collectionManager.LoadCollections()
}
// LoadCollection returns the full content of a single collection by name.
func (a *App) LoadCollection(collectionName string) (*collection.Collection, error) {
return a.collectionManager.LoadCollection(collectionName)
}
// UpdateCollection saves the changes to an entire collection.
func (a *App) UpdateCollection(updated collection.Collection) error {
return a.collectionManager.UpdateCollection(updated)
}
// DeleteCollection removes a collection by name.
func (a *App) DeleteCollection(collectionName string) error {
return a.collectionManager.DeleteCollection(collectionName)
}
// Configuration Management Methods
// GetConfiguration returns the entire application configuration object.
func (a *App) GetConfiguration() (configuration.Configuration, error) {
if a.configManager == nil {
return configuration.Configuration{}, fmt.Errorf("configuration manager not initialized")
}
return a.configManager.Get(), nil
}
// UpdateConfiguration saves the entire application configuration object.
func (a *App) UpdateConfiguration(cfg configuration.Configuration) error {
if a.configManager == nil {
return fmt.Errorf("configuration manager not initialized")
}
// Save also updates the internal in-memory config safely
return a.configManager.Save(cfg)
}
// GetDefaultConfiguration returns the default application configuration.
func (a *App) GetDefaultConfiguration() (configuration.Configuration, error) {
if a.configManager == nil {
return configuration.Configuration{}, fmt.Errorf("configuration manager not initialized")
}
return a.configManager.GetDefaultConfiguration(), nil
}
// ListSystemFonts returns installed system font families with monospace metadata.
func (a *App) ListSystemFonts(refresh bool) ([]fonts.SystemFont, error) {
return fonts.ListFamilies(refresh)
}
// Request Management Methods
// GetRequests returns all requests within a specific collection.
func (a *App) GetRequests(collectionName string) (*[]collection.Request, error) {
return a.collectionManager.GetRequests(collectionName)
}
// AddRequest adds a new request to a specific collection.
func (a *App) AddRequest(collectionName string, request collection.Request) (*collection.Request, error) {
return a.collectionManager.AddRequest(collectionName, request)
}
// AddRequestToFolder adds a new request inside a specific folder.
func (a *App) AddRequestToFolder(collectionName string, folderId string, request collection.Request) (*collection.Request, error) {
return a.collectionManager.AddRequestToFolder(collectionName, folderId, request)
}
// RemoveRequest removes a request from a collection using its ID.
func (a *App) RemoveRequest(collectionName string, requestId string) error {
return a.collectionManager.RemoveRequest(collectionName, requestId)
}
// UpdateRequest updates an existing request within a collection.
func (a *App) UpdateRequest(collectionName string, updated collection.Request) error {
return a.collectionManager.UpdateRequest(collectionName, updated)
}
// GetFolders returns all folders within a specific collection.
func (a *App) GetFolders(collectionName string) (*[]collection.Folder, error) {
return a.collectionManager.GetFolders(collectionName)
}
// GetFolder returns a folder in a collection using its ID.
func (a *App) GetFolder(collectionName string, folderId string) (*collection.Folder, error) {
return a.collectionManager.GetFolder(collectionName, folderId)
}
// AddFolder adds a new folder to a specific parent folder (or root if parent is nil/empty string).
func (a *App) AddFolder(collectionName string, parentFolderId string, folder collection.Folder) (*collection.Folder, error) {
return a.collectionManager.AddFolder(collectionName, parentFolderId, folder)
}
// RemoveFolder removes a folder from a collection using its ID.
func (a *App) RemoveFolder(collectionName string, folderId string) error {
return a.collectionManager.RemoveFolder(collectionName, folderId)
}
// UpdateFolder updates an existing folder within a collection.
func (a *App) UpdateFolder(collectionName string, updated collection.Folder) error {
return a.collectionManager.UpdateFolder(collectionName, updated)
}
// Environment Management Methods
// CreateEnvironment creates a new, empty environment.
func (a *App) CreateEnvironment(name string) error {
return a.environmentManager.CreateEnvironment(name)
}
// LoadEnvironments returns a list of all available environment names.
func (a *App) LoadEnvironments() (*[]string, error) {
return a.environmentManager.LoadEnvironments()
}
// LoadEnvironment returns the full content of a single environment by name.
func (a *App) LoadEnvironment(name string) (*environment.Environment, error) {
return a.environmentManager.LoadEnvironment(name)
}
// UpdateEnvironment saves the changes to an entire environment.
func (a *App) UpdateEnvironment(updated environment.Environment) error {
return a.environmentManager.UpdateEnvironment(&updated)
}
// DeleteEnvironment removes an environment by name.
func (a *App) DeleteEnvironment(name string) error {
return a.environmentManager.DeleteEnvironment(name)
}
// RenameEnvironment changes the name of an environment.
func (a *App) RenameEnvironment(oldName, newName string) error {
if a.environmentManager == nil {
return fmt.Errorf("environment manager not initialized")
}
return a.environmentManager.RenameEnvironment(oldName, newName)
}
// Environment Value Management Methods
// GetValues returns all key-value pairs for a specific environment.
func (a *App) GetValues(environmentName string) (*map[string]environment.ValueType, error) {
return a.environmentManager.GetValues(environmentName)
}
// AddValue adds a new variable to a specific environment.
func (a *App) AddValue(environmentName string, valueName string, value environment.ValueType) error {
return a.environmentManager.AddValue(environmentName, valueName, value)
}
// RemoveValue removes a variable from a specific environment.
func (a *App) RemoveValue(environmentName string, valueName string) error {
return a.environmentManager.RemoveValue(environmentName, valueName)
}
// UpdateValue updates an existing variable in a specific environment.
func (a *App) UpdateValue(environmentName string, valueName string, updated environment.ValueType) error {
return a.environmentManager.UpdateValue(environmentName, valueName, updated)
}
// ResolveRequestPlaceholders identifies placeholders in a request and resolves them
// using values from the specified environment.
func (a *App) ResolveRequestPlaceholders(reqId string, collName string, envId string) (*map[string]environment.ValueType, error) {
req, err := a.collectionManager.GetRequest(collName, reqId)
if err != nil {
return nil, err
}
coll, err := a.collectionManager.LoadCollection(collName)
if err != nil {
return nil, err
}
env, err := a.environmentManager.LoadEnvironment(envId)
if err != nil {
return nil, err
}
resolvedMap := make(map[string]environment.ValueType)
for _, key := range req.GetPlaceholders() {
envValue, hasEnv := env.Values[key]
collectionValue, hasCollection := coll.Variables[key]
switch {
case hasEnv && strings.TrimSpace(envValue.Value) != "":
resolvedMap[key] = envValue
case hasCollection:
resolvedMap[key] = environment.ValueType{
Value: collectionValue.Value,
Type: collectionValue.Type,
}
case hasEnv:
resolvedMap[key] = envValue
}
}
return &resolvedMap, nil
}
func (a *App) loadCollectionVariableValues(collectionName string) map[string]string {
if a.collectionManager == nil || strings.TrimSpace(collectionName) == "" {
return map[string]string{}
}
coll, err := a.collectionManager.LoadCollection(collectionName)
if err != nil {
slog.Warn("Failed to load collection variables for request execution",
"collection", collectionName,
"error", err)
return map[string]string{}
}