-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstol.go
More file actions
726 lines (634 loc) · 24.9 KB
/
instol.go
File metadata and controls
726 lines (634 loc) · 24.9 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
package main
import (
"archive/tar"
"archive/zip"
"compress/gzip"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"io/fs"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/spf13/pflag"
)
var version = "0.2.0"
// Config holds the parsed command-line configuration.
type Config struct {
URL string
InstallPath string
FileType string
Force bool
}
// AppLogger is the application-wide logger.
var AppLogger *log.Logger
// DefaultCommandExecutor is a variable holding the function to execute commands.
// It's exposed for testing purposes.
var DefaultCommandExecutor = exec.Command
// ExitFunc is a variable holding the function to exit the program.
// It's exposed for testing purposes.
var ExitFunc = os.Exit
// Stdin is a variable holding the standard input reader.
// It's exposed for testing purposes.
var Stdin io.Reader = os.Stdin
// osStat is a variable holding the os.Stat function.
// It's exposed for testing purposes.
var osStat = os.Stat
// filepathWalkDir is a variable holding the filepath.WalkDir function.
// It's exposed for testing purposes.
var filepathWalkDir = filepath.WalkDir
func init() {
// Initialize the logger to write to stderr by default.
// This setup will be reconfigured by initLogger once the main logic starts.
AppLogger = log.New(os.Stderr, "[instol] ", log.Ldate|log.Ltime|log.Lshortfile)
}
// initLogger initializes the application logger to write to a rotating file and stderr.
func initLogger() error {
logDir := filepath.Join(os.Getenv("HOME"), ".local", "share", "instol", "logs")
if err := os.MkdirAll(logDir, 0755); err != nil {
return fmt.Errorf("failed to create log directory: %w", err)
}
logFileName := fmt.Sprintf("instol-%s.log", time.Now().Format("0601")) // YYMM.log (e.g., 2507.log)
logFilePath := filepath.Join(logDir, logFileName)
file, err := os.OpenFile(logFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("failed to open log file: %w", err)
}
// Use MultiWriter to write to both file and os.Stderr
mw := io.MultiWriter(file, os.Stderr)
AppLogger = log.New(mw, "[instol] ", log.Ldate|log.Ltime|log.Lshortfile)
AppLogger.Println("Logger initialized and configured for file output.")
return nil
}
// run contains the main logic of the application, taking arguments and returning an exit code.
func run(args []string) int {
var cfg Config
cmdLine := pflag.NewFlagSet(args[0], pflag.ContinueOnError)
cmdLine.StringVarP(&cfg.InstallPath, "path", "p", "/usr/local/bin", "Specify the installation directory.")
cmdLine.StringVarP(&cfg.FileType, "type", "t", "", "Manually specify the file type (binary, compressed, deb).")
cmdLine.BoolVarP(&cfg.Force, "force", "f", false, "Overwrite existing files without prompting for confirmation.")
showVersion := cmdLine.Bool("version", false, "Display version information and exit.")
showHelp := cmdLine.BoolP("help", "h", false, "Display help information and exit.")
// Set custom usage output to stderr for consistency.
cmdLine.Usage = func() {
fmt.Fprintf(cmdLine.Output(), "instol v%s\n", version)
fmt.Fprintf(cmdLine.Output(), "Usage: %s [<options>] <url> [<output_filename>]\n", cmdLine.Name())
fmt.Fprintln(cmdLine.Output(), "\nDescription:")
fmt.Fprintln(cmdLine.Output(), " instol is a versatile command-line tool designed to simplify the installation")
fmt.Fprintln(cmdLine.Output(), " of software directly from a URL. It intelligently detects the file type")
fmt.Fprintln(cmdLine.Output(), " (.deb, compressed archive, or raw binary) and automates the entire")
fmt.Fprintln(cmdLine.Output(), " process, including download, extraction (if applicable),")
fmt.Fprintln(cmdLine.Output(), " placement in system directories, permission setting, and cleanup of temporary files.")
fmt.Fprintln(cmdLine.Output(), " This streamlines installations from sources like GitHub, Bitbucket, or direct downloads.")
fmt.Fprintln(cmdLine.Output(), "\nArguments:")
fmt.Fprintln(cmdLine.Output(), " <url> The URL of the file to install (e.g., .deb, .tar.gz, .zip, or raw binary).")
fmt.Fprintln(cmdLine.Output(), " [<output_filename>] Optional: Custom filename for the installed executable.") // Removed reference to overriding -o
fmt.Fprintln(cmdLine.Output(), "\nOptions:")
cmdLine.PrintDefaults()
fmt.Fprintln(cmdLine.Output(), "\nExamples:")
fmt.Fprintln(cmdLine.Output(), " # Install a .deb package")
fmt.Fprintln(cmdLine.Output(), " instol https://example.com/package.deb")
fmt.Fprintln(cmdLine.Output(), "\n # Install a compressed binary (e.g., .tar.gz, .zip)")
fmt.Fprintln(cmdLine.Output(), " instol https://github.com/user/repo/releases/download/v1.0.0/tool.tar.gz")
fmt.Fprintln(cmdLine.Output(), "\n # Install a raw binary with a custom name using positional argument")
fmt.Fprintln(cmdLine.Output(), " instol https://example.com/raw_binary mytool")
fmt.Fprintln(cmdLine.Output(), "\n # Install a compressed file and force overwrite")
fmt.Fprintln(cmdLine.Output(), " instol https://github.com/user/repo/releases/download/v1.0.0/tool.zip --force")
fmt.Fprintln(cmdLine.Output(), "\n # Install a binary where the URL doesn't have a clear extension, specifying type")
fmt.Fprintln(cmdLine.Output(), " instol https://example.com/download/latest_tool --type binary")
fmt.Fprintln(cmdLine.Output(), "\n # Display the tool version")
fmt.Fprintln(cmdLine.Output(), " instol --version")
}
// Parse arguments using the local FlagSet.
if err := cmdLine.Parse(args[1:]); err != nil {
if err == pflag.ErrHelp {
return 0
}
AppLogger.Printf("Error parsing arguments: %v\n", err)
cmdLine.Usage()
return 1
}
// Check for help/version flags BEFORE initializing the full logger
if *showHelp {
cmdLine.Usage()
return 0
}
if *showVersion {
fmt.Printf("instol v%s\n", version)
return 0
}
// Argument validation logic.
numArgs := cmdLine.NArg() // Number of non-flag arguments
if numArgs < 1 {
cmdLine.Usage()
return 1
}
// NOW, initialize the file logger. It will reconfigure AppLogger.
if err := initLogger(); err != nil {
// If initLogger itself fails, we must output to stderr directly.
fmt.Fprintf(os.Stderr, "Fatal: Failed to initialize file logger: %v\n", err)
return 1
}
cfg.URL = cmdLine.Arg(0)
var finalOutputFilename string // Variable to hold the determined output filename
if numArgs > 1 {
// If a positional argument for output filename is provided
finalOutputFilename = cmdLine.Arg(1)
}
if numArgs > 2 {
AppLogger.Printf("Error: Too many arguments provided.\n")
cmdLine.Usage()
return 1
}
if cfg.URL == "" {
AppLogger.Printf("Error: URL cannot be empty.\n")
cmdLine.Usage()
return 1
}
// Determine output filename if not provided by positional argument.
if finalOutputFilename == "" {
base := filepath.Base(cfg.URL)
if strings.Contains(base, "?") {
base = strings.Split(base, "?")[0]
}
finalOutputFilename = base
AppLogger.Printf("Determined output filename from URL: %s\n", finalOutputFilename)
}
// Create a temporary directory for download.
tempDir, err := os.MkdirTemp("", "instol_download_")
if err != nil {
AppLogger.Printf("Failed to create temporary directory: %v\n", err)
return 1
}
defer func() {
AppLogger.Printf("Cleaning up temporary directory: %s\n", tempDir)
os.RemoveAll(tempDir)
}()
downloadedFilePath := filepath.Join(tempDir, filepath.Base(cfg.URL)) // Use base name of URL for downloaded file
AppLogger.Printf("Attempting to download %s to %s\n", cfg.URL, downloadedFilePath)
fmt.Printf("Downloading %s to %s...\n", cfg.URL, downloadedFilePath)
if err := downloadFile(cfg.URL, downloadedFilePath); err != nil {
AppLogger.Printf("Download failed: %v\n", err)
return 1
}
AppLogger.Printf("Download of %s completed successfully.\n", cfg.URL)
fmt.Printf("Download completed to %s\n", downloadedFilePath)
// Determine file type if not specified.
if cfg.FileType == "" {
cfg.FileType = detectFileType(downloadedFilePath)
AppLogger.Printf("Detected file type: %s\n", cfg.FileType)
if cfg.FileType == "unknown" {
AppLogger.Printf("Warning: Could not automatically detect file type for %s. Attempting to install as binary.\n", downloadedFilePath)
fmt.Fprintf(os.Stderr, "Warning: Could not automatically detect file type. Attempting to install as binary.\n")
cfg.FileType = "binary" // Default to binary if detection fails
}
} else {
AppLogger.Printf("Using specified file type: %s\n", cfg.FileType)
}
// Check if install path exists and is writable.
installPathWritable, err := isWritable(cfg.InstallPath)
if err != nil {
AppLogger.Printf("Error: Cannot check writability of '%s': %v\n", cfg.InstallPath, err)
return 1
}
// Handle installation based on file type.
var installErr error
switch cfg.FileType {
case "binary":
installErr = installBinary(downloadedFilePath, cfg.InstallPath, finalOutputFilename, cfg.Force, !installPathWritable)
case "compressed":
installErr = extractAndInstallCompressed(downloadedFilePath, cfg.InstallPath, finalOutputFilename, cfg.Force, !installPathWritable)
case "deb":
installErr = installDebPackage(downloadedFilePath, !installPathWritable)
default:
AppLogger.Printf("Error: Unsupported file type: %s\n", cfg.FileType)
return 1
}
if installErr != nil {
AppLogger.Printf("Installation failed: %v\n", installErr)
return 1
}
fmt.Println("Installation completed successfully!")
AppLogger.Printf("instol tool finished successfully.\n")
return 0
}
// main is the entry point of the application.
func main() {
exitCode := run(os.Args)
ExitFunc(exitCode)
}
// downloadFile downloads a file from a URL to a specified path.
func downloadFile(url, destPath string) error {
resp, err := http.Get(url)
if err != nil {
return fmt.Errorf("failed to download file: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("bad status: %s", resp.Status)
}
out, err := os.Create(destPath)
if err != nil {
return fmt.Errorf("failed to create file %s: %w", destPath, err)
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
if err != nil {
return fmt.Errorf("failed to write file: %w", err)
}
return nil
}
// detectFileType tries to determine the file type based on extension and magic numbers (limited).
func detectFileType(filePath string) string {
ext := strings.ToLower(filepath.Ext(filePath))
// Prioritize common extensions.
switch ext {
case ".deb":
return "deb"
case ".zip":
return "compressed"
case ".tar", ".gz", ".tgz", ".bz2", ".tbz", ".xz", ".txz":
return "compressed"
}
// Basic magic number check.
file, err := os.Open(filePath)
if err != nil {
AppLogger.Printf("Error opening file for type detection: %v\n", err)
return "unknown"
}
defer file.Close()
buffer := make([]byte, 4) // Read first 4 bytes for common magic numbers.
if _, err := file.Read(buffer); err != nil {
AppLogger.Printf("Error reading file for type detection: %v\n", err)
return "unknown"
}
// ZIP: PK\x03\x04
if buffer[0] == 0x50 && buffer[1] == 0x4B && buffer[2] == 0x03 && buffer[3] == 0x04 {
return "compressed"
}
// GZIP: \x1f\x8b
if buffer[0] == 0x1f && buffer[1] == 0x8b {
return "compressed"
}
// ELF (common for Linux executables): \x7fELF
if buffer[0] == 0x7f && buffer[1] == 0x45 && buffer[2] == 0x4c && buffer[3] == 0x46 {
return "binary"
}
// If no specific type detected, assume it's unknown.
return "unknown"
}
// extractAndInstallCompressed extracts and installs executables from a compressed file.
func extractAndInstallCompressed(srcPath, installPath, outputFilename string, force, needsSudoExecution bool) error {
AppLogger.Printf("Extracting %s to temporary location and installing to %s\n", srcPath, installPath)
fmt.Println("Extracting contents...")
// Create a new temporary directory for extraction, distinct from the download location.
tempExtractDir, err := os.MkdirTemp("", "instol_extract_")
if err != nil {
AppLogger.Printf("Failed to create temporary extraction directory: %v\n", err)
return fmt.Errorf("failed to create temporary extraction directory: %w", err)
}
defer func() {
AppLogger.Printf("Cleaning up temporary extraction directory: %s\n", tempExtractDir)
os.RemoveAll(tempExtractDir)
}()
// Use the general extractArchive function.
if err := extractArchive(srcPath, tempExtractDir); err != nil {
return fmt.Errorf("extraction failed: %w", err)
}
fmt.Println("Extraction completed.")
// Find potential binaries in the extracted directory.
potentialExecutables := []string{}
// Walk through the extracted directory to find regular files (potential executables).
err = filepathWalkDir(tempExtractDir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.Type().IsRegular() {
potentialExecutables = append(potentialExecutables, path)
}
return nil
})
if err != nil {
return fmt.Errorf("failed to walk extracted directory: %w", err)
}
var targetExecutable string
if outputFilename != "" {
// Try to find an extracted file that exactly matches the desired output filename (case-insensitive).
for _, p := range potentialExecutables {
if strings.EqualFold(filepath.Base(p), outputFilename) {
targetExecutable = p
break
}
}
if targetExecutable == "" {
// If not found by exact match, and outputFilename was specified, it's a problem.
return fmt.Errorf("specified output filename '%s' not found among extracted files. Found: %v", outputFilename, potentialExecutables)
}
} else {
// If outputFilename is not provided:
if len(potentialExecutables) == 1 {
// If only one executable is found, use it.
targetExecutable = potentialExecutables[0]
} else if len(potentialExecutables) > 1 {
// If multiple executables are found, try to find one that matches the archive's base name
// or has a common executable name.
archiveBaseName := strings.TrimSuffix(filepath.Base(srcPath), filepath.Ext(srcPath))
// Prioritize a binary that matches a common pattern (e.g., "linux", "amd64") or the archive base name.
for _, p := range potentialExecutables {
base := strings.ToLower(filepath.Base(p))
if strings.Contains(base, "linux") || strings.Contains(base, "amd64") || strings.Contains(base, "x86_64") || strings.EqualFold(base, archiveBaseName) {
targetExecutable = p
break
}
}
if targetExecutable == "" {
// Fallback: error if ambiguous and no clear candidate.
return fmt.Errorf("multiple potential executable files found in archive and no specific output filename provided. Please specify using positional argument. Found: %v", potentialExecutables)
}
} else { // len(potentialExecutables) == 0
return fmt.Errorf("no executable files found in the extracted archive. Please check the archive content or specify a direct binary URL")
}
}
// At this point, targetExecutable should be the path to the file to install.
// If outputFilename was provided, use it for the final installed name.
// Otherwise, use the base name of the targetExecutable.
finalInstalledName := outputFilename
if finalInstalledName == "" {
finalInstalledName = filepath.Base(targetExecutable)
}
// Call installBinary to move and set permissions.
// The installBinary function handles checking for existence, force overwrite, and sudo.
AppLogger.Printf("Attempting to install executable %s to %s/%s\n", targetExecutable, installPath, finalInstalledName)
if err := installBinary(targetExecutable, installPath, finalInstalledName, force, needsSudoExecution); err != nil {
return fmt.Errorf("failed to install extracted file %s: %w", targetExecutable, err)
}
fmt.Println("Extraction and installation completed.")
AppLogger.Println("Extraction and installation completed.")
return nil
}
// installBinary installs a standalone executable.
func installBinary(srcPath, installPath, outputFilename string, force, needsSudoExecution bool) error {
destPath := filepath.Join(installPath, outputFilename)
if !force {
if _, err := osStat(destPath); err == nil {
fmt.Printf("File already exists: '%s'\n", destPath)
// Show details and ask for overwrite confirmation.
fmt.Printf(" Size: %d bytes\n", getFileSize(destPath))
fmt.Printf(" Last Modified: %s\n", getFileModTime(destPath))
fmt.Print("Do you want to overwrite it? (y/n): ")
var choice string
fmt.Fscanln(Stdin, &choice) // Use Stdin for testability
if strings.ToLower(choice) != "y" {
return fmt.Errorf("installation aborted by user")
}
fmt.Printf("Overwriting '%s'...\n", destPath)
} else if !os.IsNotExist(err) {
return fmt.Errorf("failed to check existing file: %w", err)
}
}
// Move the file.
mvArgs := []string{"mv", srcPath, destPath}
if needsSudoExecution {
mvArgs = append([]string{"sudo"}, mvArgs...)
}
cmd := DefaultCommandExecutor(mvArgs[0], mvArgs[1:]...)
AppLogger.Printf("Executing: %s\n", strings.Join(mvArgs, " "))
if out, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to move executable: %w\nOutput: %s", err, out)
}
// Set executable permissions.
chmodArgs := []string{"chmod", "+x", destPath}
if needsSudoExecution { // Use sudo for chmod if mv also needed sudo.
chmodArgs = append([]string{"sudo"}, chmodArgs...)
}
cmd = DefaultCommandExecutor(chmodArgs[0], chmodArgs[1:]...)
AppLogger.Printf("Executing: %s\n", strings.Join(chmodArgs, " "))
if out, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to set executable permissions: %w\nOutput: %s", err, out)
}
AppLogger.Printf("Successfully installed executable to %s\n", destPath)
fmt.Printf("Successfully installed '%s' to '%s'\n", filepath.Base(destPath), destPath)
return nil
}
// extractArchive handles extraction of .zip and common tar archives.
func extractArchive(srcPath, destDir string) error {
ext := strings.ToLower(filepath.Ext(srcPath))
switch ext {
case ".zip":
return unzip(srcPath, destDir)
case ".tar", ".gz", ".tgz", ".bz2", ".tbz", ".xz", ".txz":
return untar(srcPath, destDir)
default:
// Try to untar anyway, in case it's a tar without a standard extension.
if err := untar(srcPath, destDir); err == nil {
return nil
}
// If untar failed, try unzip as a last resort.
if err := unzip(srcPath, destDir); err == nil {
return nil
}
return fmt.Errorf("unsupported archive format or failed to extract")
}
}
// unzip extracts a zip archive.
func unzip(src, dest string) error {
r, err := zip.OpenReader(src)
if err != nil {
return err
}
defer r.Close()
for _, f := range r.File {
fpath := filepath.Join(dest, f.Name)
if !strings.HasPrefix(fpath, filepath.Clean(dest)+string(os.PathSeparator)) {
return fmt.Errorf("%s: illegal file path", fpath)
}
if f.FileInfo().IsDir() {
os.MkdirAll(fpath, os.ModePerm)
continue
}
if err = os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
return err
}
outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return err
}
rc, err := f.Open()
if err != nil {
outFile.Close()
return err
}
_, err = io.Copy(outFile, rc)
outFile.Close()
rc.Close()
if err != nil {
return err
}
}
return nil
}
// untar extracts a tar, tar.gz, tar.bz2, tar.xz archive.
func untar(src, dest string) error {
file, err := os.Open(src)
if err != nil {
return err
}
defer file.Close()
var fileReader io.Reader = file
// Handle compressed tar files using gzip reader or external tar command.
if strings.HasSuffix(src, ".gz") || strings.HasSuffix(src, ".tgz") {
gzr, err := gzip.NewReader(file)
if err != nil {
return fmt.Errorf("failed to create gzip reader: %w", err)
}
defer gzr.Close()
fileReader = gzr
} else if strings.HasSuffix(src, ".bz2") || strings.HasSuffix(src, ".tbz") {
return executeTarCommand(src, dest, "xf")
} else if strings.HasSuffix(src, ".xz") || strings.HasSuffix(src, ".txz") {
return executeTarCommand(src, dest, "xf")
}
// For plain .tar or if decompression was handled by a reader.
tarReader := tar.NewReader(fileReader)
for {
header, err := tarReader.Next()
if err == io.EOF {
break // End of archive
}
if err != nil {
return err
}
targetPath := filepath.Join(dest, header.Name)
if !strings.HasPrefix(targetPath, filepath.Clean(dest)+string(os.PathSeparator)) {
return fmt.Errorf("%s: illegal file path", targetPath)
}
switch header.Typeflag {
case tar.TypeDir:
if err := os.MkdirAll(targetPath, fs.FileMode(header.Mode)); err != nil {
return err
}
case tar.TypeReg:
if err := os.MkdirAll(filepath.Dir(targetPath), fs.FileMode(header.Mode)); err != nil {
return err
}
outFile, err := os.OpenFile(targetPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, fs.FileMode(header.Mode))
if err != nil {
return err
}
if _, err := io.Copy(outFile, tarReader); err != nil {
outFile.Close()
return err
}
outFile.Close()
default:
AppLogger.Printf("Skipping unsupported tar entry type: %v %s\n", header.Typeflag, header.Name)
}
}
return nil
}
// executeTarCommand uses the system's `tar` command for extraction.
func executeTarCommand(srcPath, destDir, action string) error {
cmdArgs := []string{action, srcPath, "-C", destDir}
cmd := DefaultCommandExecutor("tar", cmdArgs...)
AppLogger.Printf("Executing tar command: tar %s\n", strings.Join(cmdArgs, " "))
if out, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to execute tar command: %w\nOutput: %s", err, out)
}
return nil
}
// installDebPackage installs a .deb package using dpkg and apt.
func installDebPackage(debPath string, needsSudoExecution bool) error {
fmt.Printf("Installing .deb package: %s...\n", debPath)
// First, try installing with apt, which handles dependencies.
aptArgs := []string{"install", "-y", debPath}
if needsSudoExecution {
aptArgs = append([]string{"sudo"}, aptArgs...)
}
cmd := DefaultCommandExecutor(aptArgs[0], aptArgs[1:]...)
AppLogger.Printf("Executing: %s\n", strings.Join(aptArgs, " "))
if out, err := cmd.CombinedOutput(); err != nil {
AppLogger.Printf("apt install failed, trying dpkg: %v\nOutput: %s", err, out)
fmt.Fprintf(os.Stderr, "Warning: apt install failed, trying dpkg: %v\n", err)
// If apt install fails (e.g., broken dependencies), try dpkg directly.
dpkgArgs := []string{"dpkg", "-i", debPath}
if needsSudoExecution {
dpkgArgs = append([]string{"sudo"}, dpkgArgs...)
}
cmd = DefaultCommandExecutor(dpkgArgs[0], dpkgArgs[1:]...)
AppLogger.Printf("Executing: %s\n", strings.Join(dpkgArgs, " "))
if out, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to install .deb package with dpkg: %w\nOutput: %s", err, out)
}
// If dpkg succeeds but dependencies are missing, apt --fix-broken install will resolve.
AppLogger.Printf("dpkg install completed. Running apt --fix-broken install to resolve dependencies.\n")
fmt.Println("dpkg install completed. Running 'apt --fix-broken install' to resolve any missing dependencies...")
fixBrokenArgs := []string{"apt", "--fix-broken", "install", "-y"}
if needsSudoExecution {
fixBrokenArgs = append([]string{"sudo"}, fixBrokenArgs...)
}
cmd = DefaultCommandExecutor(fixBrokenArgs[0], fixBrokenArgs[1:]...)
AppLogger.Printf("Executing: %s\n", strings.Join(fixBrokenArgs, " "))
if out, err := cmd.CombinedOutput(); err != nil {
AppLogger.Printf("apt --fix-broken install failed: %v\nOutput: %s", err, out)
// This might be a warning rather than a fatal error for the deb install itself.
fmt.Fprintf(os.Stderr, "Warning: apt --fix-broken install failed: %v\n", err)
}
}
fmt.Printf("Successfully installed .deb package: %s\n", debPath)
return nil
}
// calculateSHA256 calculates the SHA256 hash of a file.
func calculateSHA256(filePath string) (string, error) {
file, err := os.Open(filePath)
if err != nil {
return "", fmt.Errorf("failed to open file for hash calculation: %w", err)
}
defer file.Close()
hash := sha256.New()
if _, err := io.Copy(hash, file); err != nil {
return "", fmt.Errorf("failed to read file for hash calculation: %w", err)
}
return hex.EncodeToString(hash.Sum(nil)), nil
}
// isWritable checks if a directory is writable by the current user.
// It's exposed for testing purposes.
var isWritable = func(dir string) (bool, error) {
info, err := osStat(dir)
if err != nil {
return false, err
}
if !info.IsDir() {
return false, fmt.Errorf("%s is not a directory", dir)
}
tempFile := filepath.Join(dir, fmt.Sprintf(".test_writable_%d", time.Now().UnixNano()))
f, err := os.Create(tempFile)
if err != nil {
return false, nil // Cannot create, likely not writable
}
f.Close()
os.Remove(tempFile) // Clean up
return true, nil
}
// getFileSize returns the size of a file in bytes.
func getFileSize(filePath string) int64 {
info, err := osStat(filePath)
if err != nil {
AppLogger.Printf("Error getting file size for %s: %v\n", filePath, err)
return 0
}
return info.Size()
}
// getFileModTime returns the last modification time of a file.
func getFileModTime(filePath string) time.Time {
info, err := osStat(filePath)
if err != nil {
AppLogger.Printf("Error getting file mod time for %s: %v\n", filePath, err)
return time.Time{}
}
return info.ModTime()
}