-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.go
647 lines (552 loc) · 15.4 KB
/
app.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"os"
"sort"
"strings"
"sync"
"time"
"os/exec"
"github.com/Jguer/go-alpm/v2"
paconf "github.com/Morganamilo/go-pacmanconf"
)
var h *alpm.Handle
// var dbs []alpm.IDB
var dbs []alpm.IDB
var DesktopEnv string
// App struct
type App struct {
ctx context.Context
}
// NewApp creates a new App application struct
func NewApp() *App {
return &App{}
}
// startup is called at application startup
func (a *App) startup(ctx context.Context) {
// Perform your setup here
a.ctx = ctx
DesktopEnv = getDesktopEnvironment()
var err error
h, err = alpm.Initialize("/", "/var/lib/pacman")
if err != nil {
fmt.Fprintf(os.Stderr, "failed to initialize alpm: %v\n", err)
os.Exit(1)
}
// Register and sync repositories
repos := []string{"core", "extra"}
for _, repo := range repos {
db, err := h.RegisterSyncDB(repo, 0)
if err != nil {
fmt.Printf("Error getting sync db for %s: %v\n", repo, err)
return
}
dbs = append(dbs, db)
}
}
// domReady is called after front-end resources have been loaded
func (a App) domReady(ctx context.Context) {
// Add your action here
}
// beforeClose is called when the application is about to quit,
// either by clicking the window close button or calling runtime.Quit.
// Returning true will cause the application to continue, false will continue shutdown as normal.
func (a *App) beforeClose(ctx context.Context) (prevent bool) {
return false
}
// shutdown is called at application termination
func (a *App) shutdown(ctx context.Context) {
// Perform your teardown here
if h != nil {
h.Release()
}
}
type PackageInfo struct {
Name string `json:"name"`
Version string `json:"version"`
Description string `json:"description"`
Repository string `json:"repository"`
Maintainer string `json:"maintainer"`
UpstreamURL string `json:"upstreamurl"`
DependList []string `json:"dependlist"`
LastUpdated string `json:"lastupdated"`
}
func (a *App) SearchPackage(query string) []PackageInfo {
var results []PackageInfo
var wg sync.WaitGroup
resultChan := make(chan PackageInfo, 100)
doneChan := make(chan bool)
// Start a goroutine to collect results
go func() {
for pkg := range resultChan {
results = append(results, pkg)
}
doneChan <- true
}()
// Search official repositories concurrently
for _, db := range dbs {
wg.Add(1)
go func(db alpm.IDB) {
defer wg.Done()
searchDB(db, query, resultChan)
}(db)
}
// Search AUR concurrently
wg.Add(1)
go func() {
defer wg.Done()
searchAUR(query, resultChan)
}()
// Wait for all searches to complete
wg.Wait()
close(resultChan)
// Wait for result collection to finish
<-doneChan
return results
}
func searchDB(db alpm.IDB, query string, resultChan chan<- PackageInfo) {
db.PkgCache().ForEach(func(pkg alpm.IPackage) error {
if strings.Contains(strings.ToLower(pkg.Name()), strings.ToLower(query)) {
lastUpdated := pkg.BuildDate().UTC().Format("Jan. 2, 2006, 3 p.m. MST")
resultChan <- PackageInfo{
Name: pkg.Name(),
Version: pkg.Version(),
Description: pkg.Description(),
Repository: db.Name(),
Maintainer: pkg.Packager(),
UpstreamURL: pkg.URL(),
DependList: convertDependList(pkg.Depends()),
LastUpdated: lastUpdated,
}
}
return nil
})
}
func searchAUR(query string, resultChan chan<- PackageInfo) {
cmd := exec.Command("curl", "-s", fmt.Sprintf("https://aur.archlinux.org/rpc/?v=5&type=search&arg=%s", query))
output, err := cmd.Output()
if err != nil {
fmt.Printf("Error searching AUR: %v\n", err)
return
}
var aurResponse struct {
Results []struct {
Name string `json:"Name"`
Version string `json:"Version"`
Description string `json:"Description"`
Maintainer string `json:"Maintainer"`
URL string `json:"URL"`
LastModified int64 `json:"LastModified"`
} `json:"results"`
}
err = json.Unmarshal(output, &aurResponse)
if err != nil {
fmt.Printf("Error parsing AUR response: %v\n", err)
return
}
for _, aurPkg := range aurResponse.Results {
lastUpdated := time.Unix(aurPkg.LastModified, 0).UTC().Format("02-01-2006")
resultChan <- PackageInfo{
Name: aurPkg.Name,
Version: aurPkg.Version,
Description: aurPkg.Description,
Repository: "AUR",
Maintainer: aurPkg.Maintainer,
UpstreamURL: aurPkg.URL,
DependList: nil,
LastUpdated: lastUpdated,
}
}
}
func convertDependList(depList alpm.IDependList) []string {
var deps []string
depList.ForEach(func(dep *alpm.Depend) error {
deps = append(deps, dep.Name)
return nil
})
return deps
}
func (a *App) GetInstalledPackages() ([]PackageInfo, error) {
h, err := alpm.Initialize("/", "/var/lib/pacman")
if err != nil {
fmt.Fprintf(os.Stderr, "failed to initialize alpm: %v\n", err)
os.Exit(1)
}
if h == nil {
return nil, fmt.Errorf("ALPM handle is not initialized")
}
db, err := h.LocalDB()
if err != nil {
return nil, fmt.Errorf("failed to get local DB: %v", err)
}
var packages []PackageInfo
var mutex sync.Mutex
err = db.PkgCache().ForEach(func(pkg alpm.IPackage) error {
mutex.Lock()
lastUpdated := pkg.BuildDate().UTC().Format("Jan. 2, 2006, 3 p.m. MST")
packages = append(packages, PackageInfo{
Name: pkg.Name(),
Version: pkg.Version(),
Description: pkg.Description(),
Repository: pkg.DB().Name(),
Maintainer: pkg.Packager(),
UpstreamURL: pkg.URL(),
DependList: convertDependList(pkg.Depends()),
LastUpdated: lastUpdated,
})
mutex.Unlock()
return nil
})
if err != nil {
return nil, fmt.Errorf("error iterating over packages: %v", err)
}
if len(packages) == 0 {
return nil, fmt.Errorf("no installed packages found")
}
return packages, nil
}
func (a *App) SearchLocalPackage(pkg string) (bool, error) {
if pkg == "" {
return false, fmt.Errorf("empty package name provided")
}
local, err := searchLocalDB(pkg)
if err != nil {
return false, fmt.Errorf("error searching local DB: %w", err)
}
if local == nil {
return false, nil
}
fmt.Println(strings.Contains(strings.ToLower(local.Name()), strings.ToLower(pkg)))
return strings.Contains(strings.ToLower(local.Name()), strings.ToLower(pkg)), nil
}
func searchLocalDB(pkg string) (alpm.IPackage, error) {
h, err := alpm.Initialize("/", "/var/lib/pacman")
if err != nil {
fmt.Fprintf(os.Stderr, "failed to initialize alpm: %v\n", err)
os.Exit(1)
}
if h == nil {
return nil, fmt.Errorf("ALPM handle is not initialized")
}
db, err := h.LocalDB()
if err != nil {
return nil, fmt.Errorf("failed to get local DB: %w", err)
}
res := db.Pkg(pkg)
return res, nil
}
func (a *App) CheckPackageInstalled(packageName string) bool {
h, err := alpm.Initialize("/", "/var/lib/pacman")
if err != nil {
fmt.Fprintf(os.Stderr, "failed to initialize alpm: %v\n", err)
os.Exit(1)
}
if h == nil {
log.Fatal("ALPM handle is not initialized")
}
localDB, err := h.LocalDB()
if err != nil {
log.Fatal(err)
}
packageHandle := localDB.Pkg(packageName)
return packageHandle != nil
}
func (a *App) Install(pkg string) {
cmdStr := fmt.Sprintf("pkexec yay -S %s --noconfirm", pkg)
cmd := exec.Command("sh", "-c", cmdStr)
fmt.Println("Executing command:", cmdStr)
var outBuffer, errBuffer bytes.Buffer
cmd.Stdout = &outBuffer
cmd.Stderr = &errBuffer
err := cmd.Run()
if err != nil {
fmt.Println("Error executing command:", err)
fmt.Println("stderr:", errBuffer.String())
return
}
fmt.Println("stdout:", outBuffer.String())
fmt.Println("stderr:", errBuffer.String())
}
func (a *App) Uninstall(pkg string) {
cmdStr := fmt.Sprintf("pkexec yay -Rdd %s --noconfirm", pkg)
cmd := exec.Command("sh", "-c", cmdStr)
fmt.Println("Executing command:", cmdStr)
var outBuffer, errBuffer bytes.Buffer
cmd.Stdout = &outBuffer
cmd.Stderr = &errBuffer
err := cmd.Run()
if err != nil {
fmt.Println("Error executing command:", err)
fmt.Println("stderr:", errBuffer.String())
return
}
fmt.Println("stdout:", outBuffer.String())
fmt.Println("stderr:", errBuffer.String())
}
// func openTerminal(cmd string) {
// var pkexecCmd *exec.Cmd
// switch DesktopEnv {
// case "xfce":
// pkexecCmd = exec.Command("xfce4-terminal", "-e", cmd)
// case "gnome":
// pkexecCmd = exec.Command("gnome-terminal", "--", "bash", "-c", cmd)
// case "kde":
// pkexecCmd = exec.Command("konsole", "-e", cmd)
// case "mate":
// pkexecCmd = exec.Command("mate-terminal", "-e", cmd)
// case "lxde":
// pkexecCmd = exec.Command("lxterminal", "-e", cmd)
// case "lxqt":
// pkexecCmd = exec.Command("qterminal", "-e", cmd)
// default:
// fmt.Printf("Unsupported desktop environment: %s\n", DesktopEnv)
// return
// }
// if err := pkexecCmd.Run(); err != nil {
// fmt.Printf("Error executing command: %v\n", err)
// }
// }
func getDesktopEnvironment() string {
return strings.ToLower(os.Getenv("XDG_CURRENT_DESKTOP"))
}
func (a *App) GetMultiplePackageInfo(packageNames []string) ([]PackageInfo, error) {
var results []PackageInfo
var wg sync.WaitGroup
resultChan := make(chan PackageInfo, len(packageNames))
errorChan := make(chan error, len(packageNames))
for _, pkgName := range packageNames {
wg.Add(1)
go func(name string) {
defer wg.Done()
// Search for package info
searchResults := a.SearchPackage(name)
var pkg PackageInfo
for _, result := range searchResults {
if result.Repository == "core" || result.Repository == "extra" || result.Repository == "AUR" {
pkg = result
pkg.Name = name // Ensure the name matches the search query
resultChan <- pkg
return
}
}
// If no package was found in core, extra, or AUR, add a placeholder
if pkg.Name == "" {
resultChan <- PackageInfo{
Name: name,
Description: "Package not found in core, extra, or AUR",
Repository: "unknown",
}
}
}(pkgName)
}
// Close channels when all goroutines are done
go func() {
wg.Wait()
close(resultChan)
close(errorChan)
}()
// Collect results and errors
for i := 0; i < len(packageNames); i++ {
select {
case result := <-resultChan:
results = append(results, result)
case err := <-errorChan:
return nil, fmt.Errorf("error processing packages: %w", err)
case <-a.ctx.Done():
return nil, a.ctx.Err()
}
}
// Sort results to maintain order of input packageNames
sort.Slice(results, func(i, j int) bool {
iIndex := indexOf(packageNames, results[i].Name)
jIndex := indexOf(packageNames, results[j].Name)
return iIndex < jIndex
})
return results, nil
}
func indexOf(slice []string, item string) int {
for i, s := range slice {
if s == item {
return i
}
}
return -1
}
type UpdateInfo struct {
Name string `json:"name"`
OldVersion string `json:"oldVersion"`
NewVersion string `json:"newVersion"`
Repository string `json:"repository"`
DownloadSize int64 `json:"downloadSize"`
}
// GetAvailableUpdates returns a list of available updates for packages
func (a *App) GetAvailableUpdates() ([]UpdateInfo, error) {
// Initialize ALPM
h, err := alpm.Initialize("/", "/var/lib/pacman")
if err != nil {
return nil, fmt.Errorf("failed to initialize alpm: %v", err)
}
defer h.Release()
// Parse pacman configuration
pacmanConfig, _, err := paconf.ParseFile("/etc/pacman.conf")
if err != nil {
return nil, fmt.Errorf("failed to parse pacman config: %v", err)
}
// Register sync databases
for _, repo := range pacmanConfig.Repos {
db, err := h.RegisterSyncDB(repo.Name, 0)
if err != nil {
return nil, fmt.Errorf("failed to register sync db %s: %v", repo.Name, err)
}
db.SetServers(repo.Servers)
}
// Get local database
localDB, err := h.LocalDB()
if err != nil {
return nil, fmt.Errorf("failed to get local DB: %v", err)
}
// Get sync databases
syncDBs, err := h.SyncDBs()
if err != nil {
return nil, fmt.Errorf("failed to get sync DBs: %v", err)
}
var updates []UpdateInfo
var mutex sync.Mutex
var wg sync.WaitGroup
// Check for updates in official repositories
wg.Add(1)
go func() {
defer wg.Done()
for _, pkg := range localDB.PkgCache().Slice() {
select {
case <-a.ctx.Done():
return
default:
newPkg := pkg.SyncNewVersion(syncDBs)
if newPkg != nil {
mutex.Lock()
updates = append(updates, UpdateInfo{
Name: pkg.Name(),
OldVersion: pkg.Version(),
NewVersion: newPkg.Version(),
Repository: newPkg.DB().Name(),
DownloadSize: newPkg.Size(),
})
mutex.Unlock()
}
}
}
}()
// Check for AUR updates
wg.Add(1)
go func() {
defer wg.Done()
aurUpdates, err := a.checkAURUpdates()
if err != nil {
log.Printf("Error checking AUR updates: %v", err)
return
}
mutex.Lock()
updates = append(updates, aurUpdates...)
mutex.Unlock()
}()
wg.Wait()
return updates, nil
}
func (a *App) checkAURUpdates() ([]UpdateInfo, error) {
var aurUpdates []UpdateInfo
// Get list of AUR packages
cmd := exec.CommandContext(a.ctx, "yay", "-Qm")
output, err := cmd.Output()
if err != nil {
return nil, fmt.Errorf("failed to get AUR package list: %v", err)
}
aurPackages := strings.Split(strings.TrimSpace(string(output)), "\n")
for _, pkg := range aurPackages {
select {
case <-a.ctx.Done():
return aurUpdates, a.ctx.Err()
default:
parts := strings.Fields(pkg)
if len(parts) != 2 {
continue
}
name, version := parts[0], parts[1]
// Check for updates using AUR RPC
cmd := exec.CommandContext(a.ctx, "curl", "-s", fmt.Sprintf("https://aur.archlinux.org/rpc/v5/info/%s", name))
output, err := cmd.Output()
if err != nil {
log.Printf("Error checking AUR for package %s: %v", name, err)
continue
}
var aurResponse struct {
Results []struct {
Version string `json:"Version"`
} `json:"results"`
}
err = json.Unmarshal(output, &aurResponse)
if err != nil {
log.Printf("Error parsing AUR response for package %s: %v", name, err)
continue
}
if len(aurResponse.Results) > 0 && aurResponse.Results[0].Version != version {
aurUpdates = append(aurUpdates, UpdateInfo{
Name: name,
OldVersion: version,
NewVersion: aurResponse.Results[0].Version,
Repository: "AUR",
DownloadSize: 0,
})
}
}
}
return aurUpdates, nil
}
// HumanReadableSize converts bytes to a human-readable string
func (a *App) HumanReadableSize(size int64) string {
floatsize := float32(size)
units := [...]string{"", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi"}
for _, unit := range units {
if floatsize < 1024 {
return fmt.Sprintf("%.1f %sB", floatsize, unit)
}
floatsize /= 1024
}
return fmt.Sprintf("%d%s", size, "B")
}
func (a *App) UpdateSinglePkg(pkg string) {
cmdStr := fmt.Sprintf("pkexec yay -S %s --noconfirm", pkg)
cmd := exec.Command("sh", "-c", cmdStr)
fmt.Println("Executing command:", cmdStr)
var outBuffer, errBuffer bytes.Buffer
cmd.Stdout = &outBuffer
cmd.Stderr = &errBuffer
err := cmd.Run()
if err != nil {
fmt.Println("Error executing command:", err)
fmt.Println("stderr:", errBuffer.String())
return
}
fmt.Println("stdout:", outBuffer.String())
fmt.Println("stderr:", errBuffer.String())
}
func (a *App) UpdateAllPkg() {
cmdStr := "pkexec yay -Syu --noconfirm"
cmd := exec.Command("sh", "-c", cmdStr)
fmt.Println("Executing command:", cmdStr)
var outBuffer, errBuffer bytes.Buffer
cmd.Stdout = &outBuffer
cmd.Stderr = &errBuffer
err := cmd.Run()
if err != nil {
fmt.Println("Error executing command:", err)
fmt.Println("stderr:", errBuffer.String())
return
}
fmt.Println("stdout:", outBuffer.String())
fmt.Println("stderr:", errBuffer.String())
}