-
-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathapp.go
More file actions
1193 lines (988 loc) · 32.6 KB
/
app.go
File metadata and controls
1193 lines (988 loc) · 32.6 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 (
"context"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
"github.com/wailsapp/wails/v2/pkg/menu"
rt "github.com/wailsapp/wails/v2/pkg/runtime"
"WailBrew/backend/brew"
"WailBrew/backend/config"
"WailBrew/backend/logging"
"WailBrew/backend/system"
"WailBrew/backend/ui"
"WailBrew/i18n"
)
// Initialize i18n FS from main package's i18n.go
func init() {
i18n.FS = i18nFS
}
var Version = "0.dev"
// Standard PATH and locale for brew commands (includes Workbrew paths for enterprise users)
const brewEnvPath = "PATH=/opt/workbrew/sbin:/opt/workbrew/bin:/opt/homebrew/sbin:/opt/homebrew/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin"
const brewEnvLang = "LANG=en_US.UTF-8"
const brewEnvLCAll = "LC_ALL=en_US.UTF-8"
const brewEnvNoAutoUpdate = "HOMEBREW_NO_AUTO_UPDATE=1"
// wailsEventEmitter implements brew.EventEmitter for Wails
// It stores the exact context from Wails lifecycle hooks
type wailsEventEmitter struct {
ctx context.Context
}
func (e *wailsEventEmitter) Emit(event string, data string) {
// Use the stored context directly - it's the exact context from startup()
if e.ctx != nil {
rt.EventsEmit(e.ctx, event, data)
}
}
// GitHubRelease represents a GitHub release
type GitHubRelease struct {
TagName string `json:"tag_name"`
Name string `json:"name"`
Body string `json:"body"`
PublishedAt string `json:"published_at"`
Assets []struct {
Name string `json:"name"`
BrowserDownloadURL string `json:"browser_download_url"`
Size int64 `json:"size"`
} `json:"assets"`
}
// UpdateInfo contains information about available updates
type UpdateInfo struct {
Available bool `json:"available"`
CurrentVersion string `json:"currentVersion"`
LatestVersion string `json:"latestVersion"`
ReleaseNotes string `json:"releaseNotes"`
DownloadURL string `json:"downloadUrl"`
FileSize int64 `json:"fileSize"`
PublishedAt string `json:"publishedAt"`
}
// NewPackagesInfo contains information about newly discovered packages
type NewPackagesInfo = brew.NewPackagesInfo
// Config represents the application configuration (see config.GetConfigPath for location)
type Config = config.Config
// App struct - minimal orchestrator
type App struct {
ctx context.Context
brewPath string
currentLanguage string
config *config.Config
askpassManager *system.Manager
sessionLogManager *logging.Manager
brewExecutor *brew.Executor
brewService brew.Service
i18nManager *i18n.Manager
eventEmitter *wailsEventEmitter
}
// detectBrewPathByArchitecture detects the brew binary path based on system architecture
// Returns the default path for the architecture, prioritizing architecture-specific paths
func detectBrewPathByArchitecture() string {
// Check for workbrew first (enterprise users)
if _, err := os.Stat("/opt/workbrew/bin/brew"); err == nil {
return "/opt/workbrew/bin/brew"
}
// Detect architecture-specific default paths
switch runtime.GOARCH {
case "arm64":
// Apple Silicon Macs
if _, err := os.Stat("/opt/homebrew/bin/brew"); err == nil {
return "/opt/homebrew/bin/brew"
}
case "amd64", "386":
// Intel Macs or Linux
if runtime.GOOS == "darwin" {
// Intel Macs
if _, err := os.Stat("/usr/local/bin/brew"); err == nil {
return "/usr/local/bin/brew"
}
} else if runtime.GOOS == "linux" {
// Linux
if _, err := os.Stat("/home/linuxbrew/.linuxbrew/bin/brew"); err == nil {
return "/home/linuxbrew/.linuxbrew/bin/brew"
}
}
}
// Fallback: try to find brew in PATH
if path, err := exec.LookPath("brew"); err == nil {
return path
}
// Final fallback: return architecture-specific default
return getArchitectureDefaultPath()
}
// getArchitectureDefaultPath returns the default brew path for the current architecture
// This is used as a fallback when no brew installation is found
func getArchitectureDefaultPath() string {
switch runtime.GOARCH {
case "arm64":
return "/opt/homebrew/bin/brew"
case "amd64", "386":
if runtime.GOOS == "darwin" {
return "/usr/local/bin/brew"
}
return "/home/linuxbrew/.linuxbrew/bin/brew"
default:
return "/opt/homebrew/bin/brew"
}
}
// detectBrewPath automatically detects the brew binary path (legacy function for compatibility)
func detectBrewPath() string {
return detectBrewPathByArchitecture()
}
// NewApp creates a new App application struct
func NewApp() *App {
brewPath := detectBrewPath()
cfg := &config.Config{}
cfg.Load() // Load config early to get admin username
// Get admin username from config, or current user as fallback
adminUsername := cfg.AdminUsername
if adminUsername == "" {
adminUsername = os.Getenv("USER")
}
app := &App{
brewPath: brewPath,
currentLanguage: "en",
config: cfg,
askpassManager: system.NewManager(adminUsername),
sessionLogManager: logging.NewManager(),
}
// Initialize brew executor with basic env (will be updated after config loads)
basicEnv := []string{
brewEnvPath,
brewEnvLang,
brewEnvLCAll,
brewEnvNoAutoUpdate,
}
app.brewExecutor = brew.NewExecutor(brewPath, basicEnv, app.sessionLogManager.Append)
// Initialize i18n manager
var err error
app.i18nManager, err = i18n.NewManager("en")
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to load translations: %v\n", err)
}
return app
}
// getBrewEnv returns the standard brew environment variables
func (a *App) getBrewEnv() []string {
env := []string{
brewEnvPath,
brewEnvLang,
brewEnvLCAll,
brewEnvNoAutoUpdate,
}
// Add proxy environment variables if configured
if a.config.Proxy != "" {
proxy := a.config.Proxy
env = append(env, fmt.Sprintf("http_proxy=%s", proxy))
env = append(env, fmt.Sprintf("https_proxy=%s", proxy))
env = append(env, fmt.Sprintf("all_proxy=%s", proxy))
env = append(env, fmt.Sprintf("HTTP_PROXY=%s", proxy))
env = append(env, fmt.Sprintf("HTTPS_PROXY=%s", proxy))
env = append(env, fmt.Sprintf("ALL_PROXY=%s", proxy))
}
// Add SUDO_ASKPASS if askpass helper is available
if a.askpassManager != nil {
askpassPath := a.askpassManager.GetPath()
if askpassPath != "" {
env = append(env, fmt.Sprintf("SUDO_ASKPASS=%s", askpassPath))
}
}
// Add mirror source environment variables if configured
if a.config.GitRemote != "" {
env = append(env, fmt.Sprintf("HOMEBREW_GIT_REMOTE=%s", a.config.GitRemote))
}
if a.config.BottleDomain != "" {
env = append(env, fmt.Sprintf("HOMEBREW_BOTTLE_DOMAIN=%s", a.config.BottleDomain))
}
// Build and add HOMEBREW_CASK_OPTS if cask options are configured
caskOpts := a.buildCaskOpts()
if caskOpts != "" {
env = append(env, fmt.Sprintf("HOMEBREW_CASK_OPTS=%s", caskOpts))
}
return env
}
// buildCaskOpts builds HOMEBREW_CASK_OPTS by merging UI-configured options with custom options
func (a *App) buildCaskOpts() string {
var opts []string
if a.config.NoQuarantine {
opts = append(opts, "--no-quarantine")
}
// Add UI-configured appdir if set
if a.config.CaskAppDir != "" {
opts = append(opts, fmt.Sprintf("--appdir=%s", a.config.CaskAppDir))
}
// Parse and append custom opts, but skip --appdir if already set via UI
if a.config.CustomCaskOpts != "" {
customParts := strings.Fields(a.config.CustomCaskOpts)
hasAppDir := a.config.CaskAppDir != ""
for _, part := range customParts {
// Skip --appdir in custom opts if already set via UI setting
if hasAppDir && strings.HasPrefix(part, "--appdir") {
continue
}
opts = append(opts, part)
}
}
return strings.Join(opts, " ")
}
// startup saves the application context and sets up services
func (a *App) startup(ctx context.Context) {
// Store the exact context from Wails lifecycle hook
// This context must be used for all EventsEmit calls
a.ctx = ctx
// Load config from file
if err := a.config.Load(); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to load config: %v\n", err)
}
// Auto-detect and set brew path if not explicitly configured
if a.config.BrewPath == "" {
// User hasn't set a path in config, use the path detected in NewApp()
// This preserves workbrew and any custom paths that were found
// Only save if the detected path actually exists (validates the detection)
if a.brewPath != "" {
if _, err := os.Stat(a.brewPath); err == nil {
// Valid path detected, save it to config
a.config.BrewPath = a.brewPath
if err := a.config.Save(); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to save auto-detected brew path: %v\n", err)
}
} else {
// Detected path doesn't exist, fall back to architecture default
archDefaultPath := getArchitectureDefaultPath()
if _, err := os.Stat(archDefaultPath); err == nil {
a.config.BrewPath = archDefaultPath
a.brewPath = archDefaultPath
if err := a.config.Save(); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to save architecture default brew path: %v\n", err)
}
}
}
}
} else {
// User has explicitly set a path in config, use it and validate it
if _, err := os.Stat(a.config.BrewPath); err == nil {
a.brewPath = a.config.BrewPath
} else {
// Config path doesn't exist, fall back to detected path
fmt.Fprintf(os.Stderr, "Warning: configured brew path %s does not exist, using detected path %s\n", a.config.BrewPath, a.brewPath)
}
}
// Update brew executor with full environment
a.brewExecutor = brew.NewExecutor(a.brewPath, a.getBrewEnv(), a.sessionLogManager.Append)
// Set up the askpass helper
if a.askpassManager != nil {
if err := a.askpassManager.Setup(); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to setup askpass helper: %v\n", err)
}
}
// Reload translations for current language
if a.i18nManager != nil {
if err := a.i18nManager.LoadLanguage(a.currentLanguage); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to load translations: %v\n", err)
}
}
// Create event emitter with the exact context from lifecycle hook
// Wails requires this exact context instance for EventsEmit to work
a.eventEmitter = &wailsEventEmitter{ctx: ctx}
// Initialize brew service with all dependencies
a.brewService = brew.NewService(
a.brewExecutor,
a.brewPath,
a.getBrewEnv,
a.sessionLogManager.Append,
func() error { return a.brewExecutor.ValidateInstallation() },
func(key string, params map[string]string) string {
if a.i18nManager != nil {
return a.i18nManager.GetBackendMessage(key, params)
}
return key
},
a.eventEmitter,
func() string { return a.GetOutdatedFlag() },
func() string { return a.GetCustomOutdatedArgs() },
brew.ExtractJSONFromOutput,
brew.ParseWarnings,
)
}
// shutdown cleans up resources when the application exits
func (a *App) shutdown(ctx context.Context) {
if a.askpassManager != nil {
a.askpassManager.Cleanup()
}
if a.sessionLogManager != nil {
a.sessionLogManager.Clear()
}
}
// menu builds the application menu using the UI module
func (a *App) menu() *menu.Menu {
return ui.Build(a)
}
// GetContext returns the application context (for ui.AppInterface)
func (a *App) GetContext() context.Context {
return a.ctx
}
// GetTranslation returns a translation (for ui.AppInterface)
func (a *App) GetTranslation(key string, params map[string]string) string {
if a.i18nManager != nil {
return a.i18nManager.GetTranslation(key, params)
}
return key
}
// OpenURL opens a URL in the browser
func (a *App) OpenURL(url string) {
rt.BrowserOpenURL(a.ctx, url)
}
// SetWindowTheme updates the native macOS window title bar appearance to match the app theme
func (a *App) SetWindowTheme(isDark bool) {
if isDark {
system.SetAppearanceDark()
} else {
system.SetAppearanceLight()
}
}
// SetLanguage updates the current language and rebuilds the menu
func (a *App) SetLanguage(language string) {
a.currentLanguage = language
if a.i18nManager != nil {
if err := a.i18nManager.LoadLanguage(language); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to load translations for %s: %v\n", language, err)
}
}
// Rebuild the menu with new language
newMenu := a.menu()
rt.MenuSetApplicationMenu(a.ctx, newMenu)
}
// GetCurrentLanguage returns the current language
func (a *App) GetCurrentLanguage() string {
return a.currentLanguage
}
// GetSessionLogs returns all session logs as a string
func (a *App) GetSessionLogs() string {
if a.sessionLogManager != nil {
return a.sessionLogManager.Get()
}
return ""
}
// BREW OPERATIONS - Delegation to brew.Service
// StartupData is the type returned by GetStartupData
type StartupData = brew.StartupData
// GetStartupData returns all initial data needed for app startup in a single call
// This is optimized to minimize duplicate brew command executions
func (a *App) GetStartupData() *StartupData {
return a.brewService.GetStartupData()
}
// GetStartupDataWithUpdate returns startup data after updating the database
func (a *App) GetStartupDataWithUpdate() *StartupData {
return a.brewService.GetStartupDataWithUpdate()
}
// ClearBrewCache clears the brew command cache (useful after install/remove operations)
func (a *App) ClearBrewCache() {
a.brewService.ClearCache()
}
func (a *App) GetAllBrewPackages() [][]string {
return a.brewService.GetAllBrewPackages()
}
func (a *App) GetAllBrewCasks() [][]string {
return a.brewService.GetAllBrewCasks()
}
func (a *App) GetBrewPackages() [][]string {
return a.brewService.GetBrewPackages()
}
func (a *App) GetBrewCasks() [][]string {
return a.brewService.GetBrewCasks()
}
func (a *App) GetBrewLeaves() []string {
return a.brewService.GetBrewLeaves()
}
func (a *App) GetBrewTaps() [][]string {
return a.brewService.GetBrewTaps()
}
func (a *App) GetBrewTapInfo(repositoryName string) string {
return a.brewService.GetBrewTapInfo(repositoryName)
}
func (a *App) GetBrewPackageSizes(packageNames []string) map[string]string {
return a.brewService.GetBrewPackageSizes(packageNames)
}
func (a *App) GetBrewCaskSizes(caskNames []string) map[string]string {
return a.brewService.GetBrewCaskSizes(caskNames)
}
func (a *App) UpdateBrewDatabase() error {
return a.brewService.UpdateBrewDatabase()
}
func (a *App) UpdateBrewDatabaseWithOutput() (string, error) {
return a.brewService.UpdateBrewDatabaseWithOutput()
}
func (a *App) ParseNewPackagesFromUpdateOutput(output string) *NewPackagesInfo {
return a.brewService.ParseNewPackagesFromUpdateOutput(output)
}
func (a *App) CheckForNewPackages() (*NewPackagesInfo, error) {
return a.brewService.CheckForNewPackages()
}
func (a *App) GetBrewUpdatablePackages() [][]string {
// Note: Database update is now handled separately via GetStartupDataWithUpdate
// or UpdateBrewDatabase to avoid redundant calls during startup
return a.brewService.GetBrewUpdatablePackages()
}
// GetBrewUpdatablePackagesWithUpdate updates the database first, then gets updatable packages
// Use this for manual refresh when you want to ensure fresh data
func (a *App) GetBrewUpdatablePackagesWithUpdate() [][]string {
// Update the formula database first to get latest information
updateOutput, err := a.brewService.UpdateBrewDatabaseWithOutput()
// DISABLED: New packages detection and toast notification disabled
// Detection logic commented out to avoid unnecessary work
/*
var newPackages *NewPackagesInfo
var shouldEmitEvent bool
// Maximum number of "new" packages to consider as a legitimate update
// If more than this, it's likely a fresh database sync (first run) rather than actual new packages
const maxReasonableNewPackages = 100
if err == nil && updateOutput != "" {
// Try to detect new packages from update output
newPackages = a.brewService.ParseNewPackagesFromUpdateOutput(updateOutput)
totalNew := len(newPackages.NewFormulae) + len(newPackages.NewCasks)
// Only emit event if there are new packages AND it's not an unreasonably large number
// (which would indicate a fresh database sync rather than actual new packages)
if totalNew > 0 && totalNew <= maxReasonableNewPackages {
shouldEmitEvent = true
}
} else {
// Fallback: try to detect new packages by comparing current list
detectedPackages, err := a.brewService.CheckForNewPackages()
if err == nil {
totalNew := len(detectedPackages.NewFormulae) + len(detectedPackages.NewCasks)
if totalNew > 0 && totalNew <= maxReasonableNewPackages {
newPackages = detectedPackages
shouldEmitEvent = true
}
}
}
// Emit event only once if new packages were discovered
if shouldEmitEvent && newPackages != nil && a.ctx != nil {
eventData := map[string]interface{}{
"newFormulae": newPackages.NewFormulae,
"newCasks": newPackages.NewCasks,
}
jsonData, _ := json.Marshal(eventData)
rt.EventsEmit(a.ctx, "newPackagesDiscovered", string(jsonData))
}
*/
_ = updateOutput // Suppress unused variable warning
_ = err // Suppress unused variable warning
return a.brewService.GetBrewUpdatablePackages()
}
func (a *App) InstallBrewPackage(packageName string) string {
return a.brewService.InstallBrewPackage(a.ctx, packageName)
}
func (a *App) RemoveBrewPackage(packageName string) string {
return a.brewService.RemoveBrewPackage(a.ctx, packageName)
}
func (a *App) UpdateBrewPackage(packageName string) string {
return a.brewService.UpdateBrewPackage(a.ctx, packageName)
}
func (a *App) UpdateSelectedBrewPackages(packageNames []string) string {
return a.brewService.UpdateSelectedBrewPackages(a.ctx, packageNames)
}
func (a *App) UpdateAllBrewPackages() string {
return a.brewService.UpdateAllBrewPackages(a.ctx)
}
func (a *App) TapBrewRepository(repositoryName string) string {
return a.brewService.TapBrewRepository(a.ctx, repositoryName)
}
func (a *App) UntapBrewRepository(repositoryName string) string {
return a.brewService.UntapBrewRepository(a.ctx, repositoryName)
}
func (a *App) GetBrewPackageInfoAsJson(packageName string) map[string]interface{} {
return a.brewService.GetBrewPackageInfoAsJson(packageName)
}
func (a *App) GetBrewPackageInfo(packageName string) string {
return a.brewService.GetBrewPackageInfo(packageName)
}
func (a *App) GetInstalledDependencies(packageName string) []string {
return a.brewService.GetInstalledDependencies(packageName)
}
func (a *App) GetInstalledDependents(packageName string) []string {
return a.brewService.GetInstalledDependents(packageName)
}
func (a *App) RunBrewDoctor() string {
return a.brewService.RunBrewDoctor()
}
func (a *App) GetDeprecatedFormulae(doctorOutput string) []string {
return a.brewService.GetDeprecatedFormulae(doctorOutput)
}
func (a *App) GetBrewCleanupDryRun() (string, error) {
return a.brewService.GetBrewCleanupDryRun()
}
func (a *App) RunBrewCleanupDryRun() string {
return a.brewService.RunBrewCleanupDryRun()
}
func (a *App) RunBrewCleanup() string {
return a.brewService.RunBrewCleanup()
}
func (a *App) GetHomebrewVersion() (string, error) {
return a.brewService.GetHomebrewVersion()
}
func (a *App) CheckHomebrewUpdate() (map[string]interface{}, error) {
return a.brewService.CheckHomebrewUpdate()
}
func (a *App) UpdateHomebrew() string {
return a.brewService.UpdateHomebrew(a.ctx)
}
func (a *App) GetHomebrewCaskVersion() (string, error) {
return a.brewService.GetHomebrewCaskVersion()
}
func (a *App) ExportBrewfile(filePath string) error {
return a.brewService.ExportBrewfile(filePath)
}
func (a *App) OpenConfigFile() error {
configPath, err := a.config.ResolvedPath()
if err != nil {
return fmt.Errorf("failed to get config path: %w", err)
}
// Ensure config file exists
if _, err := os.Stat(configPath); os.IsNotExist(err) {
// Create config file if it doesn't exist
if err := a.config.Save(); err != nil {
return fmt.Errorf("failed to create config file: %w", err)
}
}
// Open the file with the default text editor
var cmd *exec.Cmd
switch runtime.GOOS {
case "darwin":
cmd = exec.Command("open", "-t", configPath)
case "linux":
cmd = exec.Command("xdg-open", configPath)
case "windows":
cmd = exec.Command("notepad", configPath)
default:
return fmt.Errorf("unsupported operating system: %s", runtime.GOOS)
}
if err := cmd.Start(); err != nil {
return fmt.Errorf("failed to open config file: %w", err)
}
return nil
}
// CONFIG OPERATIONS - Simple delegation to config
var validLandingTabs = map[string]bool{
"installed": true,
"casks": true,
"updatable": true,
"all": true,
"allCasks": true,
"leaves": true,
"repositories": true,
"homebrew": true,
"doctor": true,
"cleanup": true,
}
func (a *App) GetLandingTab() string {
if a.config.LandingTab == "" {
return "installed"
}
return a.config.LandingTab
}
func (a *App) SetLandingTab(tab string) error {
tab = strings.TrimSpace(tab)
if !validLandingTabs[tab] {
return fmt.Errorf("invalid landing tab: %s", tab)
}
a.config.LandingTab = tab
return a.config.Save()
}
func (a *App) GetNoQuarantine() bool {
return a.config.NoQuarantine
}
func (a *App) SetNoQuarantine(val bool) error {
a.config.NoQuarantine = val
return a.config.Save()
}
func (a *App) GetProxy() string {
return a.config.Proxy
}
func (a *App) SetProxy(proxy string) error {
a.config.Proxy = strings.TrimSpace(proxy)
if err := a.config.Save(); err != nil {
return fmt.Errorf("failed to save config: %v", err)
}
// Update brew executor with new environment
if a.brewExecutor != nil {
a.brewExecutor = brew.NewExecutor(a.brewPath, a.getBrewEnv(), a.sessionLogManager.Append)
}
return nil
}
func (a *App) TestProxyConnection(proxyStr, targetUrl string) (string, error) {
proxyStr = strings.TrimSpace(proxyStr)
targetUrl = strings.TrimSpace(targetUrl)
if proxyStr == "" {
return "", fmt.Errorf("proxy URL is empty")
}
if targetUrl == "" {
return "", fmt.Errorf("target URL is empty")
}
proxyURL, err := url.Parse(proxyStr)
if err != nil {
return "", fmt.Errorf("invalid proxy URL: %v", err)
}
client := &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
},
Timeout: 10 * time.Second,
}
resp, err := client.Get(targetUrl)
if err != nil {
return "", fmt.Errorf("connection failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
return fmt.Sprintf("Success: HTTP %d", resp.StatusCode), nil
}
return fmt.Sprintf("Failed: HTTP %d", resp.StatusCode), fmt.Errorf("server returned error code: %d", resp.StatusCode)
}
func (a *App) GetMirrorSource() map[string]string {
return map[string]string{
"gitRemote": a.config.GitRemote,
"bottleDomain": a.config.BottleDomain,
}
}
func (a *App) SetMirrorSource(gitRemote string, bottleDomain string) error {
if gitRemote != "" {
if !strings.HasPrefix(gitRemote, "http://") && !strings.HasPrefix(gitRemote, "https://") {
return fmt.Errorf("invalid git remote URL: must start with http:// or https://")
}
}
if bottleDomain != "" {
if !strings.HasPrefix(bottleDomain, "http://") && !strings.HasPrefix(bottleDomain, "https://") {
return fmt.Errorf("invalid bottle domain URL: must start with http:// or https://")
}
}
a.config.GitRemote = gitRemote
a.config.BottleDomain = bottleDomain
if err := a.config.Save(); err != nil {
return fmt.Errorf("failed to save config: %v", err)
}
// Update brew executor with new environment
if a.brewExecutor != nil {
a.brewExecutor = brew.NewExecutor(a.brewPath, a.getBrewEnv(), a.sessionLogManager.Append)
}
return nil
}
func (a *App) GetOutdatedFlag() string {
flag := a.config.OutdatedFlag
if flag == "" {
return "greedy-auto-updates"
}
return flag
}
func (a *App) SetOutdatedFlag(flag string) error {
validFlags := map[string]bool{
"none": true,
"greedy": true,
"greedy-auto-updates": true,
}
if !validFlags[flag] {
return fmt.Errorf("invalid outdated flag: must be 'none', 'greedy', or 'greedy-auto-updates'")
}
a.config.OutdatedFlag = flag
if err := a.config.Save(); err != nil {
return fmt.Errorf("failed to save config: %v", err)
}
return nil
}
func (a *App) GetCaskAppDir() string {
if a.config.CaskAppDir != "" {
return a.config.CaskAppDir
}
caskOpts := os.Getenv("HOMEBREW_CASK_OPTS")
if caskOpts != "" {
re := regexp.MustCompile(`--appdir=([^\s]+)`)
matches := re.FindStringSubmatch(caskOpts)
if len(matches) > 1 {
return matches[1]
}
}
return ""
}
func (a *App) SetCaskAppDir(appDir string) error {
if appDir != "" {
if !filepath.IsAbs(appDir) {
return fmt.Errorf("cask app directory must be an absolute path")
}
appDir = strings.TrimSuffix(appDir, "/")
}
a.config.CaskAppDir = appDir
if err := a.config.Save(); err != nil {
return fmt.Errorf("failed to save config: %v", err)
}
// Update brew executor with new environment
if a.brewExecutor != nil {
a.brewExecutor = brew.NewExecutor(a.brewPath, a.getBrewEnv(), a.sessionLogManager.Append)
}
return nil
}
func (a *App) SelectCaskAppDir() (string, error) {
if a.ctx == nil {
return "", fmt.Errorf("application context not available")
}
defaultDir := a.GetCaskAppDir()
if defaultDir == "" {
defaultDir = "/Applications"
}
selectedDir, err := rt.OpenDirectoryDialog(a.ctx, rt.OpenDialogOptions{
Title: "Select Cask Application Directory",
DefaultDirectory: defaultDir,
CanCreateDirectories: true,
})
if err != nil {
return "", fmt.Errorf("failed to open directory dialog: %w", err)
}
return selectedDir, nil
}
func (a *App) GetCustomCaskOpts() string {
return a.config.CustomCaskOpts
}
func (a *App) SetCustomCaskOpts(opts string) error {
a.config.CustomCaskOpts = strings.TrimSpace(opts)
if err := a.config.Save(); err != nil {
return fmt.Errorf("failed to save config: %v", err)
}
// Update brew executor with new environment
if a.brewExecutor != nil {
a.brewExecutor = brew.NewExecutor(a.brewPath, a.getBrewEnv(), a.sessionLogManager.Append)
}
return nil
}
func (a *App) GetCustomOutdatedArgs() string {
return a.config.CustomOutdatedArgs
}
func (a *App) SetCustomOutdatedArgs(args string) error {
a.config.CustomOutdatedArgs = strings.TrimSpace(args)
if err := a.config.Save(); err != nil {
return fmt.Errorf("failed to save config: %v", err)
}
return nil
}
func (a *App) GetAdminUsername() string {
if a.config.AdminUsername == "" {
// Default to current user
return os.Getenv("USER")
}
return a.config.AdminUsername
}
func (a *App) SetAdminUsername(username string) error {
a.config.AdminUsername = strings.TrimSpace(username)
if err := a.config.Save(); err != nil {
return fmt.Errorf("failed to save config: %v", err)
}
// Update askpass manager with new default username
if a.askpassManager != nil {
adminUsername := a.config.AdminUsername
if adminUsername == "" {
adminUsername = os.Getenv("USER")
}
// Recreate the askpass manager with the new username
a.askpassManager.Cleanup()
a.askpassManager = system.NewManager(adminUsername)
// Re-setup the askpass helper
if err := a.askpassManager.Setup(); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to re-setup askpass helper: %v\n", err)
}
}
return nil
}
func (a *App) GetBrewPath() string {
// Return from config if set, otherwise return current brewPath
if a.config.BrewPath != "" {
return a.config.BrewPath
}
return a.brewPath
}
func (a *App) SetBrewPath(path string) error {
if _, err := os.Stat(path); err != nil {
return fmt.Errorf("brew path does not exist: %s", path)
}
cmd := exec.Command(path, "--version")
if err := cmd.Run(); err != nil {
return fmt.Errorf("invalid brew executable: %s", path)
}
// Update both config and runtime path
a.config.BrewPath = path
a.brewPath = path
// Save to config file
if err := a.config.Save(); err != nil {
return fmt.Errorf("failed to save brew path to config: %w", err)
}
// Update brew executor with new path
if a.brewExecutor != nil {
a.brewExecutor = brew.NewExecutor(a.brewPath, a.getBrewEnv(), a.sessionLogManager.Append)
}
return nil
}
func (a *App) GetAppVersion() string {
return Version
}
// GetMacOSVersion returns the macOS version
func (a *App) GetMacOSVersion() (string, error) {
return system.GetMacOSVersion()
}