forked from zyedidia/eget
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinstalled.go
More file actions
870 lines (750 loc) · 22 KB
/
Copy pathinstalled.go
File metadata and controls
870 lines (750 loc) · 22 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
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/BurntSushi/toml"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/sahilm/fuzzy"
)
type InstalledEntry struct {
Repo string `toml:"repo"`
Target string `toml:"target"`
InstalledAt time.Time `toml:"installed_at"`
URL string `toml:"url"`
Asset string `toml:"asset"`
Tool string `toml:"tool,omitempty"`
ExtractedFiles []string `toml:"extracted_files"`
Options map[string]interface{} `toml:"options"`
Version string `toml:"version,omitempty"`
Tag string `toml:"tag,omitempty"`
ReleaseDate time.Time `toml:"release_date,omitempty"`
}
type InstalledConfig struct {
Installed map[string]InstalledEntry `toml:"installed"`
}
type UpgradeCandidate struct {
Repo string
Entry InstalledEntry
}
type UpgradeResult struct {
Repo string
Current string
Latest string
Action string // "upgrade", "skip", "error"
Error string
}
// getInstalledConfigPath returns the path to the installed packages config file
func getInstalledConfigPath() string {
homePath, _ := os.UserHomeDir()
// Use the same logic as existing config but for installed.toml
configPath := filepath.Join(homePath, ".eget.installed.toml")
// Check if it exists, if not try the XDG config directory
if _, err := os.Stat(configPath); os.IsNotExist(err) {
var configDir string
switch runtime.GOOS {
case "windows":
configDir = os.Getenv("LOCALAPPDATA")
default:
configDir = os.Getenv("XDG_CONFIG_HOME")
}
if configDir == "" {
configDir = filepath.Join(homePath, ".config")
}
xdgPath := filepath.Join(configDir, "eget", "installed.toml")
return xdgPath
}
return configPath
}
// loadInstalledConfig loads the installed packages config from file
func loadInstalledConfig() (*InstalledConfig, error) {
configPath := getInstalledConfigPath()
var config InstalledConfig
_, err := toml.DecodeFile(configPath, &config)
if err != nil && !os.IsNotExist(err) {
return nil, fmt.Errorf("failed to load installed config: %w", err)
}
if config.Installed == nil {
config.Installed = make(map[string]InstalledEntry)
}
return &config, nil
}
// saveInstalledConfig saves the installed packages config to file
func saveInstalledConfig(config *InstalledConfig) error {
configPath := getInstalledConfigPath()
// Create directory if it doesn't exist
dir := filepath.Dir(configPath)
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("failed to create config directory: %w", err)
}
file, err := os.Create(configPath)
if err != nil {
return fmt.Errorf("failed to create config file: %w", err)
}
defer file.Close()
encoder := toml.NewEncoder(file)
if err := encoder.Encode(config); err != nil {
return fmt.Errorf("failed to encode config: %w", err)
}
return nil
}
// normalizeRepoName converts various target formats to a consistent repo key
func normalizeRepoName(target string) string {
// Handle GitHub URLs
if strings.Contains(target, "github.com/") {
// Extract user/repo from github.com/user/repo or full URLs
parts := strings.Split(target, "github.com/")
if len(parts) > 1 {
path := parts[1]
// Remove trailing slashes and .git
path = strings.TrimSuffix(path, "/")
path = strings.TrimSuffix(path, ".git")
// Take only user/repo part
if idx := strings.Index(path, "/"); idx > 0 {
repoPart := path[:idx+1+strings.Index(path[idx+1:], "/")]
if repoPart == "" {
repoPart = path
}
return strings.TrimSuffix(repoPart, "/")
}
return path
}
}
// For direct repo names like "user/repo"
if strings.Count(target, "/") == 1 && !strings.Contains(target, "://") {
return target
}
// For other URLs or local paths, use as-is but clean up
return strings.TrimSuffix(target, "/")
}
// extractOptionsMap converts Flags struct to a map for TOML storage
func extractOptionsMap(opts Flags) map[string]interface{} {
options := make(map[string]interface{})
// Only store meaningful options that affect installation
if opts.Tag != "" {
options["tag"] = opts.Tag
}
if opts.System != "" {
options["system"] = opts.System
}
if opts.Output != "" {
options["output"] = opts.Output
}
if opts.ExtractFile != "" {
options["extract_file"] = opts.ExtractFile
}
if opts.All {
options["all"] = opts.All
}
if opts.Quiet {
options["quiet"] = opts.Quiet
}
if opts.DLOnly {
options["download_only"] = opts.DLOnly
}
if opts.UpgradeOnly {
options["upgrade_only"] = opts.UpgradeOnly
}
if len(opts.Asset) > 0 {
options["asset"] = opts.Asset
}
if opts.Hash {
options["hash"] = opts.Hash
}
if opts.Verify != "" {
options["verify"] = opts.Verify
}
if opts.DisableSSL {
options["disable_ssl"] = opts.DisableSSL
}
return options
}
// getReleaseInfo fetches tag and release date from GitHub API
func getReleaseInfo(repo, url string) (string, time.Time, error) {
// Extract repo from URL if it's a GitHub URL
var apiURL string
if strings.Contains(url, "github.com/") && strings.Contains(url, "/releases/download/") {
// Parse GitHub release URL to get repo and tag
parts := strings.Split(url, "github.com/")
if len(parts) < 2 {
return "", time.Time{}, fmt.Errorf("invalid GitHub URL")
}
pathParts := strings.Split(parts[1], "/")
if len(pathParts) < 4 {
return "", time.Time{}, fmt.Errorf("invalid GitHub release URL")
}
repoName := pathParts[0] + "/" + pathParts[1]
tag := pathParts[3] // tag is in position 3 for /releases/download/tag/asset
apiURL = fmt.Sprintf("https://api.github.com/repos/%s/releases/tags/%s", repoName, tag)
} else if strings.Contains(repo, "/") {
// For direct repo names, we need to find which tag was used
// This is more complex, so for now we'll leave it empty
return "", time.Time{}, nil
} else {
return "", time.Time{}, nil
}
// Make API request
resp, err := http.Get(apiURL)
if err != nil {
return "", time.Time{}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", time.Time{}, nil // Don't fail if we can't get release info
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", time.Time{}, err
}
var release struct {
TagName string `json:"tag_name"`
CreatedAt time.Time `json:"created_at"`
}
err = json.Unmarshal(body, &release)
if err != nil {
return "", time.Time{}, err
}
return release.TagName, release.CreatedAt, nil
}
// recordInstallation records a successful installation
func recordInstallation(target, url, tool string, opts Flags, extractedFiles []string) error {
config, err := loadInstalledConfig()
if err != nil {
return err
}
repoKey := normalizeRepoName(target)
// Try to get release information
tag, releaseDate, _ := getReleaseInfo(repoKey, url)
entry := InstalledEntry{
Repo: repoKey,
Target: target,
InstalledAt: time.Now(),
URL: url,
Asset: filepath.Base(url),
Tool: tool,
ExtractedFiles: extractedFiles,
Options: extractOptionsMap(opts),
Tag: tag,
ReleaseDate: releaseDate,
}
// Store entry
if config.Installed == nil {
config.Installed = make(map[string]InstalledEntry)
}
config.Installed[repoKey] = entry
return saveInstalledConfig(config)
}
// removeInstalled removes an installed package from tracking
func removeInstalled(target string) error {
config, err := loadInstalledConfig()
if err != nil {
return err
}
repoKey := normalizeRepoName(target)
delete(config.Installed, repoKey)
return saveInstalledConfig(config)
}
// listInstalled displays all installed packages
func listInstalled() error {
config, err := loadInstalledConfig()
if err != nil {
return err
}
if len(config.Installed) == 0 {
fmt.Println("No packages installed.")
return nil
}
fmt.Println("Installed packages:")
fmt.Println()
for _, entry := range config.Installed {
fmt.Printf("%s\n", entry.Repo)
fmt.Printf(" Target: %s\n", entry.Target)
fmt.Printf(" Installed: %s\n", entry.InstalledAt.Format("2006-01-02 15:04:05"))
if len(entry.ExtractedFiles) == 1 {
fmt.Printf(" File: %s\n", entry.ExtractedFiles[0])
} else {
fmt.Printf(" Files: %s\n", strings.Join(entry.ExtractedFiles, ", "))
}
if len(entry.Options) > 0 {
var opts []string
for k, v := range entry.Options {
opts = append(opts, fmt.Sprintf("%s=%v", k, v))
}
fmt.Printf(" Options: %s\n", strings.Join(opts, ", "))
}
fmt.Println()
}
return nil
}
// checkForUpgrade checks if a package has a newer version available
func checkForUpgrade(entry InstalledEntry) (bool, string, error) {
// For GitHub repos, check if there's a newer release
if !strings.Contains(entry.Repo, "/") {
return false, "", fmt.Errorf("non-GitHub repos not supported for upgrade checks")
}
// Create a GithubAssetFinder to check for newer releases
finder := &GithubAssetFinder{
Repo: entry.Repo,
Tag: "latest",
Prerelease: false, // Only check stable releases
MinTime: entry.ReleaseDate,
}
// If we find assets, it means there's a newer release
_, err := finder.Find()
if err == ErrNoUpgrade {
// No upgrade available
return false, entry.Tag, nil
} else if err != nil {
return false, "", err
}
// There are assets, so there's an upgrade available
// Get the latest tag
latestTag, err := getLatestTag(entry.Repo)
if err != nil {
return false, "", err
}
return true, latestTag, nil
}
// getLatestTag gets the latest stable release tag for a repo
func getLatestTag(repo string) (string, error) {
url := fmt.Sprintf("https://api.github.com/repos/%s/releases/latest", repo)
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("GitHub API returned status %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
var release struct {
TagName string `json:"tag_name"`
Prerelease bool `json:"prerelease"`
}
err = json.Unmarshal(body, &release)
if err != nil {
return "", err
}
if release.Prerelease {
// If latest is a pre-release, we might need to find the latest stable
// For simplicity, we'll accept it for now
}
return release.TagName, nil
}
// performUpgrade performs an upgrade for a single package
func performUpgrade(entry InstalledEntry, newTag string) error {
// This is complex - we need to recreate the installation process
// For now, we'll use a simplified approach by calling eget recursively
// In a full implementation, this would parse the stored options and recreate the installation
// Extract options back to command line args
args := []string{entry.Target}
// Add stored options
opts := entry.Options
if tag, ok := opts["tag"].(string); ok && tag != "" {
args = append(args, "--tag", newTag) // Use new tag instead of old
} else {
args = append(args, "--tag", newTag) // Force the new tag
}
if system, ok := opts["system"].(string); ok && system != "" {
args = append(args, "--system", system)
}
if extractFile, ok := opts["extract_file"].(string); ok && extractFile != "" {
args = append(args, "--file", extractFile)
}
if all, ok := opts["all"].(bool); ok && all {
args = append(args, "--all")
}
if quiet, ok := opts["quiet"].(bool); ok && quiet {
args = append(args, "--quiet")
}
// Handle asset filters - support both []interface{} (from memory) and []string (from TOML decode)
if assetsRaw, ok := opts["asset"]; ok {
switch assets := assetsRaw.(type) {
case []interface{}:
for _, asset := range assets {
if assetStr, ok := asset.(string); ok {
args = append(args, "--asset", assetStr)
}
}
case []string:
for _, assetStr := range assets {
args = append(args, "--asset", assetStr)
}
}
}
if output, ok := opts["output"].(string); ok && output != "" {
args = append(args, "--to", output)
}
if dlOnly, ok := opts["download_only"].(bool); ok && dlOnly {
args = append(args, "--download-only")
}
if verify, ok := opts["verify"].(string); ok && verify != "" {
args = append(args, "--verify-sha256", verify)
}
if disableSSL, ok := opts["disable_ssl"].(bool); ok && disableSSL {
args = append(args, "--disable-ssl")
}
if hash, ok := opts["hash"].(bool); ok && hash {
args = append(args, "--sha256")
}
if upgradeOnly, ok := opts["upgrade_only"].(bool); ok && upgradeOnly {
args = append(args, "--upgrade-only")
}
// Get the path to eget binary
egetPath, err := os.Executable()
if err != nil {
return err
}
// Run eget with the constructed arguments
cmd := exec.Command(egetPath, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
return cmd.Run()
}
// updateInstalledRecord updates the installed record after successful upgrade
func updateInstalledRecord(repo, newTag string) error {
config, err := loadInstalledConfig()
if err != nil {
return err
}
if entry, exists := config.Installed[repo]; exists {
entry.Tag = newTag
entry.InstalledAt = time.Now()
// Note: We could fetch the new release date here, but for simplicity
// we'll leave it as-is since the upgrade succeeded
config.Installed[repo] = entry
return saveInstalledConfig(config)
}
return fmt.Errorf("package %s not found in installed records", repo)
}
// upgradeAllPackages checks and upgrades all installed packages
func upgradeAllPackages(dryRun, interactive bool) ([]UpgradeResult, error) {
config, err := loadInstalledConfig()
if err != nil {
return nil, err
}
// Convert installed entries to candidates
candidates := make([]UpgradeCandidate, 0, len(config.Installed))
for repo, entry := range config.Installed {
candidates = append(candidates, UpgradeCandidate{
Repo: repo,
Entry: entry,
})
}
// If interactive mode, let user select which packages to check
if interactive && len(candidates) > 0 {
candidates = selectPackagesInteractively(candidates)
}
results := make([]UpgradeResult, 0, len(candidates))
for _, candidate := range candidates {
result := UpgradeResult{Repo: candidate.Repo, Current: candidate.Entry.Tag}
needsUpgrade, latestTag, err := checkForUpgrade(candidate.Entry)
if err != nil {
result.Action = "error"
result.Error = err.Error()
} else if !needsUpgrade {
result.Action = "skip"
result.Latest = latestTag
} else {
result.Action = "upgrade"
result.Latest = latestTag
if !dryRun {
err := performUpgrade(candidate.Entry, latestTag)
if err != nil {
result.Action = "error"
result.Error = err.Error()
} else {
// Update the installed record
updateErr := updateInstalledRecord(candidate.Repo, latestTag)
if updateErr != nil {
// Log but don't fail the upgrade
result.Error = fmt.Sprintf("upgrade succeeded but record update failed: %v", updateErr)
}
}
}
}
results = append(results, result)
}
return results, nil
}
// Bubbletea model for interactive package selection
type packageSelectModel struct {
candidates []UpgradeCandidate
cursor int
selected map[int]bool
done bool
// fuzzy search related fields
searchInput textinput.Model
searching bool
filtered []int
}
func (m *packageSelectModel) Init() tea.Cmd {
// Initialize search input with placeholder
m.searchInput = textinput.New()
m.searchInput.Placeholder = "Search packages..."
return nil
}
// findOrInitFiltered ensures a filtered list exists and resets cursor
func (m *packageSelectModel) findOrInitFiltered() {
if m.filtered == nil {
m.filtered = make([]int, len(m.candidates))
for i := range m.candidates {
m.filtered[i] = i
}
}
m.cursor = 0
}
// applySearchFilter updates the filtered list based on searchInput value
func (m *packageSelectModel) applySearchFilter() {
query := strings.TrimSpace(m.searchInput.Value())
if query == "" {
m.filtered = make([]int, len(m.candidates))
for i := range m.candidates {
m.filtered[i] = i
}
m.cursor = 0
return
}
targets := make([]string, len(m.candidates))
for i, c := range m.candidates {
targets[i] = c.Repo
}
matches := fuzzy.Find(query, targets)
m.filtered = make([]int, 0, len(matches))
for _, mm := range matches {
m.filtered = append(m.filtered, mm.Index)
}
if len(m.filtered) == 0 {
m.cursor = 0
} else if m.cursor >= len(m.filtered) {
m.cursor = len(m.filtered) - 1
}
}
func (m *packageSelectModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
// Enter search mode with '/'
if !m.searching && msg.String() == "/" {
m.findOrInitFiltered()
m.searching = true
m.searchInput.Focus()
return m, nil
}
// When searching, check for navigation/exit keys FIRST (before routing to textinput)
if m.searching {
switch msg.String() {
case "esc":
// Cancel search mode and clear filter
m.searching = false
m.searchInput = textinput.New()
m.searchInput.Placeholder = "Search packages..."
m.filtered = nil
m.cursor = 0
return m, nil
case "enter":
// Leave search mode but keep current filter
m.searching = false
m.cursor = 0
return m, nil
case "up", "k":
if m.cursor > 0 {
m.cursor--
}
return m, nil
case "down", "j":
if m.cursor < len(m.filtered)-1 {
m.cursor++
}
return m, nil
case " ":
// Toggle selection on current filtered item
if len(m.filtered) > 0 {
idx := m.filtered[m.cursor]
if m.selected[idx] {
delete(m.selected, idx)
} else {
m.selected[idx] = true
}
}
return m, nil
case "ctrl+c":
m.done = true
return m, tea.Quit
}
// For all other keys, route to textinput for typing
newInput, cmd := m.searchInput.Update(msg)
m.searchInput = newInput
m.applySearchFilter()
return m, cmd
}
// Normal navigation/selection (when not searching)
switch msg.String() {
case "ctrl+c", "q":
m.done = true
return m, tea.Quit
case "esc":
m.done = true
return m, tea.Quit
case "enter", " ":
// Toggle selection
if m.selected[m.cursor] {
delete(m.selected, m.cursor)
} else {
m.selected[m.cursor] = true
}
case "up", "k":
if m.cursor > 0 {
m.cursor--
}
case "down", "j":
if m.cursor < len(m.candidates)-1 {
m.cursor++
}
case "a", "ctrl+a":
// Select all
for i := range m.candidates {
m.selected[i] = true
}
case "n", "ctrl+n":
// Select none
m.selected = make(map[int]bool)
case "ctrl+d":
// Done
m.done = true
return m, tea.Quit
}
}
return m, nil
}
func (m *packageSelectModel) View() string {
if m.done {
return ""
}
var b strings.Builder
b.WriteString("Select packages to check for updates:\n\n")
// Show search input when in search mode
if m.searching {
b.WriteString(m.searchInput.View())
b.WriteString("\n")
}
// Determine which indices to display: filtered if in search, otherwise all
var display []int
if m.searching {
display = m.filtered
} else {
display = make([]int, len(m.candidates))
for i := range m.candidates {
display[i] = i
}
}
for i, candidateIndex := range display {
candidate := m.candidates[candidateIndex]
cursor := " "
if m.cursor == i {
cursor = ">"
}
checkbox := "[ ]"
if m.selected[candidateIndex] {
checkbox = "[✓]"
}
current := candidate.Entry.Tag
if current == "" {
current = "unknown"
}
b.WriteString(fmt.Sprintf("%s %s %s (current: %s)\n", cursor, checkbox, candidate.Repo, current))
}
b.WriteString("\n")
if m.searching {
b.WriteString("↑/↓: navigate items • space/enter: toggle • enter: keep filter • esc: clear filter\n")
} else {
b.WriteString("↑/↓ or j/k: navigate • /: search • space/enter: toggle • a: select all • n: select none\n")
b.WriteString("ctrl+d: confirm • q/esc: quit\n")
}
return b.String()
}
// selectPackagesInteractively allows users to select which packages to upgrade using bubbletea
func selectPackagesInteractively(candidates []UpgradeCandidate) []UpgradeCandidate {
if len(candidates) == 0 {
return candidates
}
// Check if we're in an interactive terminal
if !isInteractiveTerminal() {
fmt.Fprintf(os.Stderr, "Warning: not running in interactive terminal, proceeding with all packages\n")
return candidates
}
// Create and run the bubbletea program
model := &packageSelectModel{
candidates: candidates,
selected: make(map[int]bool),
done: false,
}
// Initialize internal state
model.Init()
model.findOrInitFiltered()
model.applySearchFilter()
p := tea.NewProgram(model)
finalModel, err := p.Run()
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: interactive selection failed (%v), proceeding with all packages\n", err)
return candidates
}
m := finalModel.(*packageSelectModel)
// Collect selected candidates
selected := make([]UpgradeCandidate, 0, len(m.selected))
for idx := range m.selected {
selected = append(selected, candidates[idx])
}
return selected
}
// isInteractiveTerminal checks if we're running in an interactive terminal
func isInteractiveTerminal() bool {
// Check if stdout is a terminal
fileInfo, err := os.Stdout.Stat()
if err != nil {
return false
}
return (fileInfo.Mode() & os.ModeCharDevice) != 0
}
// displayUpgradeResults shows the results of the upgrade-all operation
func displayUpgradeResults(results []UpgradeResult, dryRun bool) {
if dryRun {
fmt.Println("Dry run - the following packages would be upgraded:")
} else {
fmt.Println("Upgrade results:")
}
fmt.Println()
upgraded := 0
skipped := 0
errors := 0
for _, result := range results {
switch result.Action {
case "upgrade":
if dryRun {
fmt.Printf("✓ %s: %s → %s (would upgrade)\n", result.Repo, result.Current, result.Latest)
} else {
fmt.Printf("✓ %s: %s → %s (upgraded)\n", result.Repo, result.Current, result.Latest)
}
upgraded++
case "skip":
fmt.Printf("• %s: %s (up to date)\n", result.Repo, result.Current)
skipped++
case "error":
fmt.Printf("✗ %s: %s\n", result.Repo, result.Error)
errors++
}
}
fmt.Println()
fmt.Printf("Summary: %d upgraded, %d skipped, %d errors\n", upgraded, skipped, errors)
}