-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
658 lines (575 loc) · 15.8 KB
/
main.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
648
649
650
651
652
653
654
655
656
657
658
package main
import (
"flag"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"github.com/lawl/ayy/appimage"
"github.com/lawl/ayy/bytesz"
"github.com/lawl/ayy/fancy"
"github.com/lawl/ayy/integrate"
"github.com/lawl/ayy/squashfs"
"github.com/lawl/ayy/update"
)
var WARNING string
var ERROR string
var INFO string
func init() {
fp := fancy.Print{}
WARNING = fp.Bold().Color(fancy.Yellow).Format("WARNING: ")
fp = fancy.Print{}
ERROR = fp.Bold().Color(fancy.Red).Format("ERROR: ")
fp = fancy.Print{}
INFO = fp.Bold().Color(fancy.Cyan).Format("INFO: ")
}
func main() {
flag.Usage = func() {
fmt.Fprint(os.Stderr,
"usage ayy <command>\n"+
"\n"+
" install Install an AppImage and integrate it into the desktop environment\n"+
" remove Locate installed AppImage by name, uninstall and unintegrate it\n"+
" upgrade Update all images in Applications folder\n"+
" list Display installed AppImages\n"+
" alias Manage aliases for AppImage in PATH\n"+
" show Show details of an AppImage\n"+
" fs Interact with an AppImage's internal filesystem\n"+
" inspect Inspect an AppImage file. Development command. Dumps assorted information.\n"+
" help Display this help\n"+
"\n"+
"Call these commands without any arguments for per command help.\n"+
"\n")
flag.PrintDefaults()
}
flag.Parse()
if flag.NArg() < 1 {
flag.Usage()
os.Exit(1)
}
switch flag.Arg(0) {
case "inspect":
inspect := flag.NewFlagSet("inspect", flag.ExitOnError)
inspect.Usage = func() {
fmt.Fprintf(os.Stderr, "usage: ayy inspect /foo/bar.AppImage\n"+
"\n")
inspect.PrintDefaults()
}
inspect.Parse(flag.Args()[1:])
if inspect.NArg() < 1 {
inspect.Usage()
os.Exit(1)
}
fp := fancy.Print{}
fp.Color(fancy.Yellow)
for _, arg := range inspect.Args() {
ai := ai(arg)
updInfo, err := ai.ELFSectionAsString(".upd_info")
if err != nil {
fmt.Fprintf(os.Stderr, ERROR+"reading update info: %s\n", err)
}
sha256sig, err := ai.ELFSectionAsString(".sha256_sig")
if err != nil {
fmt.Fprintf(os.Stderr, ERROR+"reading update info: %s\n", err)
}
sigKey, err := ai.ELFSectionAsString(".sig_key")
if err != nil {
fmt.Fprintf(os.Stderr, ERROR+"reading update info: %s\n", err)
}
fmt.Printf("%s: %d\n", fp.Format("Image Format Type"), ai.ImageFormatType)
fmt.Printf("%s: %s\n", fp.Format("Update"), updInfo)
fmt.Printf("%s:\n%s\n", fp.Format("Raw Signature"), string(sha256sig))
fmt.Printf("%s:\n%s\n", fp.Format("Raw Signature Key"), string(sigKey))
printAppImageDetails(arg)
}
case "fs":
fs := flag.NewFlagSet("fs", flag.ExitOnError)
fs.Usage = func() {
fmt.Fprintf(os.Stderr,
"usage: ayy fs /foo/bar.AppImage command\n"+
"\n"+
"commands:\n"+
" ls <path> List files under the specified path inside the AppImage\n"+
" cat <path> Print the file at <path> inside the AppImage to stdout\n"+
"\n")
fs.PrintDefaults()
}
fs.Parse(flag.Args()[1:])
if fs.NArg() < 1 {
fs.Usage()
os.Exit(1)
}
file := fs.Arg(0)
switch fs.Arg(1) {
case "ls":
ls := flag.NewFlagSet("ls", flag.ExitOnError)
ls.Usage = func() {
fmt.Fprintf(os.Stderr,
"usage: ayy fs /foo/bar.AppImage ls <path inside appimage>\n"+
"\n")
ls.PrintDefaults()
}
usebytes := ls.Bool("b", false, "Display sizes in bytes instead of human readable string")
if err := ls.Parse(fs.Args()[2:]); err != nil {
fmt.Fprintf(os.Stderr, ERROR+"Unable to parse flags: %s\n", err)
os.Exit(1)
}
if ls.NArg() < 1 {
ls.Usage()
os.Exit(1)
}
for _, arg := range ls.Args() {
fmt.Printf("%s:\n", arg)
listFiles(file, ls.Arg(0), *usebytes)
}
os.Exit(0)
case "cat":
cat := flag.NewFlagSet("cat", flag.ExitOnError)
cat.Usage = func() {
fmt.Fprintf(os.Stderr,
"usage: ayy fs /foo/bar.AppImage cat <path to file inside appimage>\n"+
"\n")
cat.PrintDefaults()
}
if err := cat.Parse(fs.Args()[2:]); err != nil {
fmt.Fprintf(os.Stderr, ERROR+"Unable to parse flags: %s\n", err)
os.Exit(1)
}
if cat.NArg() < 1 {
cat.Usage()
os.Exit(1)
}
for _, arg := range cat.Args() {
catFile(file, arg)
}
os.Exit(0)
default:
fs.Usage()
os.Exit(1)
}
case "lmao":
fmt.Println("ayy lmao")
os.Exit(0)
case "install":
install := flag.NewFlagSet("install", flag.ExitOnError)
install.Usage = func() {
fmt.Fprintf(os.Stderr, "usage: ayy install /foo/bar.AppImage\n"+
"\n"+
"this is currently required to be a local path, but may also allow https urls in the future. Stay tuned.\n"+
"\n")
install.PrintDefaults()
}
install.Parse(flag.Args()[1:])
if install.NArg() < 1 {
install.Usage()
os.Exit(1)
}
for _, arg := range install.Args() {
_, err := integrate.Install(arg, "")
if err != nil {
fmt.Fprintf(os.Stderr, ERROR+"Cannot install AppImage: %s\n", err)
os.Exit(1)
}
}
os.Exit(0)
case "remove":
remove := flag.NewFlagSet("remove", flag.ExitOnError)
id := remove.Bool("id", false, "use id instead of name")
remove.Usage = func() {
fmt.Fprintf(os.Stderr, "usage: ayy remove <name>\n"+
"\n"+
"Hint: Find names with 'ayy list'\n"+
"\n")
remove.PrintDefaults()
}
remove.Parse(flag.Args()[1:])
if remove.NArg() < 1 {
remove.Usage()
os.Exit(1)
}
for _, arg := range remove.Args() {
path := findAppImagefromCLIArgs(arg, *id)
if err := integrate.Unintegrate(path); err != nil {
fmt.Fprintf(os.Stderr, ERROR+"Unable to unintegrate AppImage: %s\n", err)
os.Exit(1)
}
if err := os.Remove(path); err != nil {
fmt.Fprintf(os.Stderr, ERROR+"Unable delete AppImage file '%s': %s\n", path, err)
os.Exit(1)
}
}
os.Exit(0)
case "upgrade":
// TODO: support arguments, so that e.g. "ayy upgrade foo bar" only updates foo and bar
appList, _ := integrate.List()
parallelUpgrade(appList)
os.Exit(0)
case "show":
show := flag.NewFlagSet("show", flag.ExitOnError)
id := show.Bool("id", false, "use id instead of name")
show.Usage = func() {
fmt.Fprintf(os.Stderr, "usage: ayy show <name>\n"+
"\n"+
"Hint: Find names with 'ayy list'\n"+
"\n")
show.PrintDefaults()
}
show.Parse(flag.Args()[1:])
if show.NArg() < 1 {
show.Usage()
os.Exit(1)
}
for _, arg := range show.Args() {
path := findAppImagefromCLIArgs(arg, *id)
printAppImageDetails(path)
}
os.Exit(0)
case "list":
listAppimages()
os.Exit(0)
case "alias":
alias := flag.NewFlagSet("alias", flag.ExitOnError)
id := alias.Bool("id", false, "use id instead of name")
add := alias.String("add", "", "Add an alias")
remove := alias.String("remove", "", "Remove an alias")
list := alias.Bool("list", false, "List all aliases")
alias.Usage = func() {
fmt.Fprintf(os.Stderr, "usage: ayy alias <name>\n"+
"\n"+
"Hint: Find names with 'ayy list'\n"+
"\n")
alias.PrintDefaults()
}
alias.Parse(flag.Args()[1:])
if *list {
l := integrate.ListPathWrappers()
yellow := fancy.Print{}
yellow.Color(fancy.Yellow)
cyan := fancy.Print{}
cyan.Color(fancy.Cyan)
for _, pwe := range l {
wrapperName := pwe.WrapperName
appName := pwe.AppImagePath
ai := ai(pwe.AppImagePath)
entryName := ai.DesktopEntry("Name")
if entryName != "" {
appName = cyan.Format(entryName)
}
fmt.Printf("%s %s %s\n", wrapperName, yellow.Format(" => "), appName)
}
os.Exit(0)
}
if *remove != "" {
if err := integrate.RemovePathWrapper(*remove); err != nil {
fmt.Fprintf(os.Stderr, ERROR+"not removing wrapper: %s\n", err)
os.Exit(1)
}
os.Exit(0)
}
if alias.NArg() < 1 {
alias.Usage()
os.Exit(1)
}
path := findAppImagefromCLIArgs(alias.Arg(0), *id)
if *add != "" {
if err := integrate.CreatePathWrapper(*add, path); err != nil {
fmt.Fprintf(os.Stderr, ERROR+"cannot create wrapper: %s\n", err)
os.Exit(1)
}
os.Exit(0)
}
//printaliases()
os.Exit(0)
case "help", "-h", "--help":
flag.Usage()
os.Exit(0)
default:
flag.Usage()
os.Exit(1)
}
}
func ai(path string) *appimage.AppImage {
app, err := appimage.Open(path)
if err != nil {
fmt.Fprintf(os.Stderr, ERROR+"Couldn't open AppImage: %s\n", err)
os.Exit(1)
}
return app
}
func unrootPath(s string) string {
return strings.TrimLeft(s, string(os.PathSeparator))
}
func listAppimages() {
lst, nNotAI := integrate.List()
cyan := fancy.Print{}
cyan.Color(fancy.Cyan)
normal := fancy.Print{}
tbl := newTable(40, -1).withFormatters(cyan, normal)
tbl.printHead("Name", "ID")
for _, v := range lst {
ai := ai(v)
defer ai.Close()
name := ai.DesktopEntry("Name")
id := ai.ID()
tbl.printRow(name, string(id))
}
if nNotAI > 0 {
fmt.Println()
fmt.Fprintf(os.Stdout, INFO+"%d files in Application folder are not AppImages.\n", nNotAI)
}
}
func printAppImageDetails(path string) error {
info, err := os.Stat(path)
if err != nil {
return err
}
if info.IsDir() {
return nil
}
ai := ai(path)
name := ai.DesktopEntry("Name")
version := ai.DesktopEntry("X-AppImage-Version")
appstreamid := ai.ID()
cyan := fancy.Print{}
cyan.Color(fancy.Cyan)
yellow := fancy.Print{}
yellow.Color(fancy.Yellow)
nocolor := fancy.Print{}
nocolor.Color(fancy.Red).Dim().Bold()
yescolor := fancy.Print{}
yescolor.Color(fancy.Green).Dim().Bold()
no := nocolor.Format("no")
yes := yescolor.Format("yes")
installedStr := no
if integrate.IsIntegrated(ai) {
installedStr = yes
}
hasOkSig := false
wrappers := integrate.PathWrappersForAppImage(path)
wrapperNames := make([]string, len(wrappers))
for i, pwe := range wrappers {
wrapperNames[i] = pwe.WrapperName
}
wrapperstr := strings.Join(wrapperNames, ", ")
updater, err := update.Info(path)
if err != nil {
return err
}
fmt.Printf("Name: %s\n"+
"\t Version: %s\n"+
"\tInstalled: %s\n"+
"\t Aliases: %s\n"+
"\t Updates: %s\n"+
"\t Path: %s\n"+
"\t ID: %s\n"+
"",
cyan.Format(name), yellow.Format(version), installedStr, wrapperstr, updater.InfoString(), path, appstreamid)
fmt.Print("\tSignature: ")
if ai.HasSignature() {
sig, ok, err := ai.Signature()
if err == nil {
if ok {
hasOkSig = true
fmt.Printf("%s ", yes)
fmt.Printf("[Primary Key ID: %s] (trust on first use)\n", sig.PrimaryKey.KeyIdString())
idprint := fancy.Print{}
idprint.Color(fancy.Yellow)
for _, i := range sig.Identities {
fmt.Printf("\t %s: %s\n", idprint.Format("Identity"), i.Name)
}
}
}
}
if !hasOkSig {
fmt.Printf("%s\n", no)
}
return nil
}
func findAppImagefromCLIArgs(name string, id bool) string {
if id {
path, found, err := integrate.FindImageById(appimage.AppImageID(name))
if err != nil {
fmt.Fprintf(os.Stderr, ERROR+"searching images: %s\n", err)
os.Exit(1)
}
fp := fancy.Print{}
fp.Color(fancy.Cyan)
if !found {
fmt.Fprintf(os.Stderr, ERROR+"No image matching ID '%s' found\n", fp.Format(name))
os.Exit(1)
}
return path
}
path, found, err := integrate.FindImageByName(name)
if err != nil {
fmt.Fprintf(os.Stderr, ERROR+"searching images: %s\n", err)
os.Exit(1)
}
fp := fancy.Print{}
fp.Color(fancy.Cyan)
if !found {
fmt.Fprintf(os.Stderr, ERROR+"No image matching name '%s' found\n", fp.Format(name))
os.Exit(1)
}
return path
}
type progressReport struct {
id int
percent int
terminated bool
text string
err error
jobindex int
appname string
}
type upgradeJob struct {
appImagePath string
jobindex int
}
func parallelUpgrade(filesToProcess []string) {
const maxConcurrency = 10
percentDone := make(chan progressReport)
jobs := make(chan upgradeJob)
defer close(percentDone)
var progressBars [maxConcurrency]fancy.ProgressBar
spawned := 0
concurrencyCount := len(filesToProcess)
if len(filesToProcess) > maxConcurrency {
concurrencyCount = maxConcurrency
}
//spawn workers
for i := 0; i < concurrencyCount; i++ {
progressBars[i] = *fancy.NewProgressBar(20, 100)
fmt.Println("") // reserve a line to print status
go upgradeWorker(percentDone, i, jobs)
spawned++
}
fancy.CursorSave()
//go routine to feed workers
go func() {
for i := range filesToProcess {
jobject := upgradeJob{appImagePath: filesToProcess[i], jobindex: i}
jobs <- jobject
}
close(jobs)
}()
fp := fancy.Print{}
fp.Color(fancy.Cyan)
errors := make([]error, len(filesToProcess))
// status printer
for {
if spawned == 0 {
break
}
status := <-percentDone
if status.terminated {
spawned--
continue
}
if status.err != nil {
errors[status.jobindex] = fmt.Errorf("Error updating '%s': %w\n", status.appname, status.err)
continue
}
fancy.CursorRestore()
fancy.CursorUp(status.id + 1)
fancy.CursorColumn(0)
fancy.EraseRemainingLine()
progressBars[status.id].Print(status.percent)
fmt.Print(" " + fp.Format(status.appname) + " " + status.text)
}
fancy.CursorRestore()
for _, err := range errors {
if err != nil {
fmt.Printf(ERROR+" %s\n", err)
}
}
}
func upgradeWorker(status chan progressReport, workerid int, jobs chan upgradeJob) {
newjob:
for job := range jobs {
progress := make(chan update.Progress)
go update.AppImage(job.appImagePath, progress)
for p := range progress {
if p.Err != nil {
status <- progressReport{id: workerid, percent: 100, appname: p.AppName, text: "Error", err: p.Err}
break newjob
}
status <- progressReport{id: workerid, percent: p.Percent, appname: p.AppName, text: p.Text}
}
}
status <- progressReport{terminated: true}
}
func listFiles(aiPath, internalPath string, usebytes bool) {
ai := ai(aiPath)
entries, err := fs.ReadDir(ai.FS, unrootPath(internalPath))
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't list directory: %s\n", err)
os.Exit(1)
}
for _, e := range entries {
info, err := e.Info()
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to fetch file info for '%s': %s", e.Name(), err)
}
sqinfo, ok := info.Sys().(squashfs.SquashInfo)
if !ok {
fmt.Fprintln(os.Stderr, "FileInfo must implement SquashInfo. This is a bug in the code.")
os.Exit(1)
}
linkTarget := ""
isSymlink := info.Mode()&fs.ModeSymlink == fs.ModeSymlink
if isSymlink {
linkTarget = " -> "
targetname := sqinfo.SymlinkTarget()
if !filepath.IsAbs(targetname) {
targetname = filepath.Join(unrootPath(internalPath), targetname)
}
target, err := ai.FS.Open(targetname)
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't read symlink pointing to %s: %s", targetname, err)
}
targetstat, err := target.Stat()
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't stat symlink target %s: %s", sqinfo.SymlinkTarget(), err)
}
linkTarget += colorizeFilename(sqinfo.SymlinkTarget(), targetstat)
}
name := colorizeFilename(e.Name(), info)
var size string
if !usebytes {
size = bytesz.Format(uint64(info.Size()))
} else {
size = fmt.Sprintf("%10d", info.Size())
}
fmt.Printf("%s %4d %4d %s %s %s%s\n", info.Mode(), sqinfo.Uid(), sqinfo.Gid(), size, info.ModTime().Format("Jan 02 2006 15:04"), name, linkTarget)
}
}
func colorizeFilename(name string, info fs.FileInfo) string {
isSymlink := info.Mode()&fs.ModeSymlink == fs.ModeSymlink
fp := fancy.Print{}
if info.IsDir() {
fp.Bold().Color(fancy.Blue)
} else if isSymlink {
fp.Bold().Color(fancy.Cyan)
} else if isExecutableBySomeone(info.Mode()) {
fp.Bold().Color(fancy.Green)
}
return fp.Format(name)
}
func isExecutableBySomeone(mode os.FileMode) bool {
return mode&0111 != 0
}
func catFile(aiPath, internalPath string) {
ai := ai(aiPath)
file, err := ai.FS.Open(unrootPath(internalPath))
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't open file: %s\n", err)
os.Exit(1)
}
_, err = io.Copy(os.Stdout, file)
if err != nil {
fmt.Fprintf(os.Stderr, "error copying file to stdout: %s", err)
}
}