-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
975 lines (826 loc) · 26.3 KB
/
main.go
File metadata and controls
975 lines (826 loc) · 26.3 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
package main
import (
"archive/tar"
"archive/zip"
"bufio"
"compress/gzip"
"encoding/json"
"flag"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"os/user"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/fatih/color"
)
type GoVersion struct {
Version string `json:"version"`
Stable bool `json:"stable"`
}
// progressReader is a custom io.Reader that tracks download progress
type progressReader struct {
reader io.Reader
totalBytes int64
readBytes int64
lastPercentage int
lastUpdateTime time.Time
}
func newProgressReader(reader io.Reader, totalBytes int64) *progressReader {
return &progressReader{
reader: reader,
totalBytes: totalBytes,
lastUpdateTime: time.Now(),
}
}
func (pr *progressReader) Read(p []byte) (int, error) {
n, err := pr.reader.Read(p)
pr.readBytes += int64(n)
// Update progress every 100ms to avoid too many updates
if time.Since(pr.lastUpdateTime) > 100*time.Millisecond {
percentage := int(float64(pr.readBytes) / float64(pr.totalBytes) * 100)
// Only update if percentage changed
if percentage != pr.lastPercentage && percentage <= 100 {
pr.lastPercentage = percentage
pr.lastUpdateTime = time.Now()
// Create progress bar (Windows-compatible approach)
progressBar := renderProgressBar(percentage)
// Print the progress bar
fmt.Print(progressBar)
}
}
return n, err
}
// renderProgressBar creates a progress bar string that works on all platforms
func renderProgressBar(percentage int) string {
// Ensure percentage is within bounds
if percentage < 0 {
percentage = 0
} else if percentage > 100 {
percentage = 100
}
// Calculate the width of the progress bar (50 characters)
width := 50
completed := width * percentage / 100
// Build the progress bar
var sb strings.Builder
// Use carriage return to return to beginning of line
sb.WriteString("\r")
// Write the progress bar
sb.WriteString("Downloading: [")
sb.WriteString(strings.Repeat("=", completed))
if completed < width {
sb.WriteString(strings.Repeat(" ", width-completed))
}
sb.WriteString("] ")
// Write the percentage
sb.WriteString(fmt.Sprintf("%3d%%", percentage))
return sb.String()
}
// printUsage prints the usage information for the getgo command
func printUsage() {
bold := color.New(color.Bold).SprintFunc()
cyan := color.New(color.FgCyan).SprintFunc()
fmt.Printf("%s: getgo [options] [version] [install_path]\n", bold("Usage"))
fmt.Printf("%s:\n", bold("Examples"))
fmt.Printf(" %s # Latest version in ~/.go\n", cyan("getgo"))
fmt.Printf(" %s # Latest version in ~/.go\n", cyan("getgo latest"))
fmt.Printf(" %s # Specific version in ~/.go\n", cyan("getgo 1.23.1"))
fmt.Printf(" %s # Specific version in /usr/local/go\n", cyan("getgo 1.23.1 /usr/local/go"))
fmt.Printf(" %s # Latest, no prompts (for scripts/Docker)\n", cyan("getgo -u"))
fmt.Printf(" %s # Custom GOPATH\n", cyan("getgo --path ~/custom/gopath"))
fmt.Printf("\n%s:\n", bold("Options"))
fmt.Printf(" -h, --help Show this help message\n")
fmt.Printf(" -u, --unattended Skip prompts and automatically set up environment variables\n")
fmt.Printf(" -p, --path PATH Set custom GOPATH (default is $HOME/go)\n")
fmt.Printf(" --envrc PATH Create a .envrc file with Go environment variables at the specified path\n")
}
func main() {
// Define flags
helpFlag := flag.Bool("help", false, "Show usage information")
hFlag := flag.Bool("h", false, "Show usage information")
unattendedFlag := flag.Bool("unattended", false, "Skip prompts and automatically set up environment variables")
uFlag := flag.Bool("u", false, "Skip prompts and automatically set up environment variables (shorthand)")
gopathFlag := flag.String("path", "", "Custom GOPATH (default is $HOME/go)")
gopathShortFlag := flag.String("p", "", "Custom GOPATH (shorthand)")
envrcFlag := flag.String("envrc", "", "Path to add .envrc file with Go environment variables")
flag.Parse()
args := flag.Args()
// Check if help was requested
if isHelpRequested(helpFlag, hFlag) {
printUsage()
os.Exit(0)
}
unattended := isUnattendedMode(unattendedFlag, uFlag)
// Default values
versionArg := "latest"
installPath := "~/.go" // Default to ~/.go
// Parse arguments based on how many are provided
switch len(args) {
case 0:
// Use defaults (latest version, ~/.go)
case 1:
versionArg = args[0]
case 2:
versionArg = args[0]
installPath = args[1]
default:
printUsage()
os.Exit(1)
}
// Expand and convert installPath to absolute path
installPath = expandPathOrExit(installPath)
// Get the user's home directory
usr, err := user.Current()
if err != nil {
color.Red("Error getting current user: %v", err)
os.Exit(1)
}
// Set GOPATH - use custom path if provided, otherwise default to $HOME/go
gopath := filepath.Join(usr.HomeDir, "go")
customPath := getCustomGOPATH(gopathFlag, gopathShortFlag)
if customPath != "" {
gopath = expandPathOrExit(customPath)
}
// Get the version to download
version := versionArg
if version == "latest" || version == "-" {
var err error
color.Cyan("Fetching latest Go version...")
version, err = getLatestGoVersion()
if err != nil {
color.Red("Error getting latest Go version: %v", err)
os.Exit(1)
}
color.Green("Latest Go version is %s", version)
}
// Create the download URL
osName := runtime.GOOS
arch := runtime.GOARCH
var archiveExt string
if osName == "windows" {
archiveExt = "zip"
} else {
archiveExt = "tar.gz"
}
downloadURL := fmt.Sprintf("https://go.dev/dl/go%s.%s-%s.%s", version, osName, arch, archiveExt)
// Versioned directory: e.g. ~/.go/go1.26.1
versionedGoDir := filepath.Join(installPath, fmt.Sprintf("go%s", version))
versionedGoDir = expandPathOrExit(versionedGoDir)
// The "current" symlink: e.g. ~/.go/current -> ~/.go/go1.26.1
currentLink := filepath.Join(installPath, "current")
// GOROOT always points to the stable symlink
goroot := currentLink
if _, err := os.Stat(versionedGoDir); err == nil {
color.Yellow("Go version %s already exists at %s", version, versionedGoDir)
// Update the current symlink
updateCurrentSymlink(currentLink, versionedGoDir)
// Ensure GOPATH directory exists
ensureDir(gopath)
// Set up environment
setupEnvIfNeeded(goroot, gopath, unattended)
setupEnvrcIfRequested(envrcFlag, goroot, gopath)
os.Exit(0)
}
// Create the installation directory if it doesn't exist
if err := os.MkdirAll(installPath, 0755); err != nil {
color.Red("Error creating installation directory: %v", err)
os.Exit(1)
}
// Download the Go archive
color.Cyan("Downloading Go %s for %s/%s...", version, osName, arch)
archivePath := filepath.Join(os.TempDir(), fmt.Sprintf("go%s.%s-%s.%s", version, osName, arch, archiveExt))
err = downloadFileWithProgress(downloadURL, archivePath)
if err != nil {
if strings.Contains(err.Error(), "404") {
color.Red("Error: Go version %s not found for %s/%s", version, osName, arch)
fmt.Println("Please check that the version exists at https://go.dev/dl/")
} else {
color.Red("Error downloading Go archive: %v", err)
}
os.Exit(1)
}
fmt.Println() // Add a newline after progress bar
// Extract the archive
color.Cyan("Extracting to %s ...", installPath)
// Create a temporary directory for extraction
tempDir, err := os.MkdirTemp("", "getgo-extract")
if err != nil {
color.Red("Error creating temporary directory: %v", err)
os.Exit(1)
}
defer os.RemoveAll(tempDir)
if osName == "windows" {
err = unzip(archivePath, tempDir)
} else {
err = untargz(archivePath, tempDir)
}
if err != nil {
color.Red("Error extracting archive: %v", err)
os.Exit(1)
}
// Move the extracted "go" directory to the versioned directory
extractedGoDir := filepath.Join(tempDir, "go")
// Remove the destination directory if it already exists
if _, err := os.Stat(versionedGoDir); err == nil {
if err := os.RemoveAll(versionedGoDir); err != nil {
color.Red("Error removing existing directory: %v", err)
os.Exit(1)
}
}
// Create the parent directory if it doesn't exist
if err := os.MkdirAll(filepath.Dir(versionedGoDir), 0755); err != nil {
color.Red("Error creating parent directory: %v", err)
os.Exit(1)
}
// Move the extracted directory to the versioned directory.
// Use os.Rename first; fall back to copy+remove for cross-device moves.
if err := os.Rename(extractedGoDir, versionedGoDir); err != nil {
if err := copyDir(extractedGoDir, versionedGoDir); err != nil {
color.Red("Error copying extracted directory: %v", err)
os.Exit(1)
}
os.RemoveAll(extractedGoDir)
}
// Clean up the downloaded archive
os.Remove(archivePath)
color.Green("Go %s has been successfully installed to %s", version, versionedGoDir)
// Update the current symlink
updateCurrentSymlink(currentLink, versionedGoDir)
// Ensure GOPATH directory exists
ensureDir(gopath)
// Set up environment
setupEnvIfNeeded(goroot, gopath, unattended)
setupEnvrcIfRequested(envrcFlag, goroot, gopath)
}
// updateCurrentSymlink creates or updates the "current" symlink to point to the given version directory.
func updateCurrentSymlink(linkPath, targetDir string) {
// Remove existing symlink or file
os.Remove(linkPath)
if err := os.Symlink(targetDir, linkPath); err != nil {
color.Yellow("Warning: could not create symlink %s -> %s: %v", linkPath, targetDir, err)
color.Yellow("GOROOT should be set to %s directly", targetDir)
return
}
color.Green("Symlink %s -> %s", linkPath, targetDir)
}
// ensureDir creates a directory if it doesn't exist.
func ensureDir(path string) {
if _, err := os.Stat(path); os.IsNotExist(err) {
if err := os.MkdirAll(path, 0755); err != nil {
color.Yellow("Warning: could not create directory %s: %v", path, err)
}
}
}
// promptYesNo asks the user a yes/no question and returns true for yes.
func promptYesNo(question string) bool {
reader := bufio.NewReader(os.Stdin)
fmt.Printf("%s [Y/n] ", question)
answer, _ := reader.ReadString('\n')
answer = strings.TrimSpace(strings.ToLower(answer))
return answer == "" || answer == "y" || answer == "yes"
}
// setupEnvIfNeeded checks shell rc files for GOROOT/GOPATH and prompts the user to update them.
// In unattended mode, it writes without prompting.
func setupEnvIfNeeded(goroot, gopath string, unattended bool) {
// Print the env vars the user needs
printEnvVars(goroot, gopath)
if unattended {
setupEnvironmentVariables(goroot, gopath)
return
}
// Interactive mode: check if env vars already exist, then ask
shellConfigFile := getShellConfigFile()
if shellConfigFile == "" {
color.Yellow("Could not determine shell configuration file. Please set up environment variables manually.")
return
}
content, err := os.ReadFile(shellConfigFile)
if err != nil && !os.IsNotExist(err) {
color.Yellow("Could not read %s: %v", shellConfigFile, err)
return
}
if strings.Contains(string(content), "GOROOT=") {
color.Yellow("Go environment variables already exist in %s", shellConfigFile)
if promptYesNo("Update them?") {
removeGoEnvBlock(shellConfigFile)
writeGoEnvBlock(shellConfigFile, goroot, gopath)
}
} else {
if promptYesNo(fmt.Sprintf("Add Go environment variables to %s?", shellConfigFile)) {
writeGoEnvBlock(shellConfigFile, goroot, gopath)
}
}
}
// setupEnvironmentVariables sets up environment variables in the appropriate configuration files.
func setupEnvironmentVariables(goroot, gopath string) {
if runtime.GOOS == "windows" {
setupWindowsEnvironment(goroot, gopath)
return
}
shellConfigFile := getShellConfigFile()
if shellConfigFile == "" {
color.Yellow("Could not determine shell configuration file. Please set up environment variables manually.")
return
}
// Remove old block if present, then write fresh
removeGoEnvBlock(shellConfigFile)
writeGoEnvBlock(shellConfigFile, goroot, gopath)
}
const goEnvMarkerStart = "# Go environment variables added by getgo"
const goEnvMarkerEnd = "# end getgo"
// writeGoEnvBlock appends the Go env block to the given shell config file.
func writeGoEnvBlock(shellConfigFile, goroot, gopath string) {
// Create the file if it doesn't exist
if _, err := os.Stat(shellConfigFile); os.IsNotExist(err) {
if _, err := os.Create(shellConfigFile); err != nil {
color.Red("Error creating %s: %v", shellConfigFile, err)
return
}
}
f, err := os.OpenFile(shellConfigFile, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
color.Red("Error opening %s: %v", shellConfigFile, err)
return
}
defer f.Close()
block := fmt.Sprintf("\n%s\nexport GOROOT=%s\nexport GOPATH=%s\nexport PATH=$GOPATH/bin:$GOROOT/bin:$PATH\n%s\n",
goEnvMarkerStart, goroot, gopath, goEnvMarkerEnd)
if _, err := f.WriteString(block); err != nil {
color.Red("Error writing to %s: %v", shellConfigFile, err)
return
}
color.Green("Go environment variables have been added to %s", shellConfigFile)
color.Yellow("Run 'source %s' to apply the changes to your current shell", shellConfigFile)
}
// removeGoEnvBlock removes the getgo env block from the given shell config file if present.
func removeGoEnvBlock(shellConfigFile string) {
content, err := os.ReadFile(shellConfigFile)
if err != nil {
return
}
lines := strings.Split(string(content), "\n")
var result []string
inBlock := false
for _, line := range lines {
if strings.TrimSpace(line) == goEnvMarkerStart {
inBlock = true
continue
}
if inBlock && strings.TrimSpace(line) == goEnvMarkerEnd {
inBlock = false
continue
}
if !inBlock {
result = append(result, line)
}
}
// Trim trailing empty lines that were left behind
for len(result) > 0 && result[len(result)-1] == "" {
result = result[:len(result)-1]
}
result = append(result, "") // ensure trailing newline
os.WriteFile(shellConfigFile, []byte(strings.Join(result, "\n")), 0644)
}
// setupWindowsEnvironment sets up environment variables in Windows
func setupWindowsEnvironment(goroot, gopath string) {
// Use PowerShell to set environment variables
color.Cyan("Setting up environment variables using PowerShell...")
// Set GOROOT
cmd := exec.Command("powershell", "-Command",
fmt.Sprintf("[Environment]::SetEnvironmentVariable('GOROOT', '%s', 'User')", goroot))
err := cmd.Run()
if err != nil {
color.Red("Error setting GOROOT: %v", err)
return
}
// Set GOPATH
cmd = exec.Command("powershell", "-Command",
fmt.Sprintf("[Environment]::SetEnvironmentVariable('GOPATH', '%s', 'User')", gopath))
err = cmd.Run()
if err != nil {
color.Red("Error setting GOPATH: %v", err)
return
}
// Update PATH
cmd = exec.Command("powershell", "-Command", `
$currentPath = [Environment]::GetEnvironmentVariable('PATH', 'User')
$goPathBin = Join-Path -Path $env:GOPATH -ChildPath 'bin'
$goRootBin = Join-Path -Path $env:GOROOT -ChildPath 'bin'
if (-not $currentPath.Contains($goPathBin) -and -not $currentPath.Contains($goRootBin)) {
$newPath = $goPathBin + ';' + $goRootBin + ';' + $currentPath
[Environment]::SetEnvironmentVariable('PATH', $newPath, 'User')
}
`)
err = cmd.Run()
if err != nil {
color.Red("Error updating PATH: %v", err)
return
}
color.Green("Go environment variables have been set up successfully")
color.Yellow("Please restart your terminal or system for the changes to take effect")
}
// getShellConfigFile determines the appropriate shell configuration file
func getShellConfigFile() string {
// Get the current shell
shell := os.Getenv("SHELL")
// Get the user's home directory
usr, err := user.Current()
if err != nil {
return ""
}
// Determine the configuration file based on the shell
switch {
case strings.Contains(shell, "zsh"):
return filepath.Join(usr.HomeDir, ".zshrc")
case strings.Contains(shell, "bash"):
// Check for .bash_profile first on macOS
if runtime.GOOS == "darwin" {
bashProfile := filepath.Join(usr.HomeDir, ".bash_profile")
if _, err := os.Stat(bashProfile); err == nil {
return bashProfile
}
}
return filepath.Join(usr.HomeDir, ".bashrc")
case strings.Contains(shell, "fish"):
fishConfig := filepath.Join(usr.HomeDir, ".config", "fish", "config.fish")
// Create the directory if it doesn't exist
os.MkdirAll(filepath.Dir(fishConfig), 0755)
return fishConfig
default:
// Try to find a common shell configuration file
for _, file := range []string{".profile", ".bashrc", ".bash_profile", ".zshrc"} {
path := filepath.Join(usr.HomeDir, file)
if _, err := os.Stat(path); err == nil {
return path
}
}
}
// Default to .profile if no other file is found
return filepath.Join(usr.HomeDir, ".profile")
}
// printEnvVars prints the environment variables needed for Go based on the OS
func printEnvVars(goroot, gopath string) {
bold := color.New(color.Bold).SprintFunc()
if runtime.GOOS == "windows" {
fmt.Printf("\n%s:\n\n", bold("Go environment variables"))
fmt.Printf("GOROOT=%s\n", goroot)
fmt.Printf("GOPATH=%s\n", gopath)
fmt.Printf("PATH=%%GOPATH%%\\bin;%%GOROOT%%\\bin;%%PATH%%\n")
} else {
fmt.Printf("\n%s:\n\n", bold("Go environment variables"))
fmt.Printf("export GOROOT=%s\n", goroot)
fmt.Printf("export GOPATH=%s\n", gopath)
fmt.Printf("export PATH=$GOPATH/bin:$GOROOT/bin:$PATH\n")
}
fmt.Println()
}
func getLatestGoVersion() (string, error) {
resp, err := http.Get("https://go.dev/dl/?mode=json")
if err != nil {
return "", err
}
defer resp.Body.Close()
var versions []GoVersion
err = json.NewDecoder(resp.Body).Decode(&versions)
if err != nil {
return "", err
}
if len(versions) == 0 {
return "", fmt.Errorf("no Go versions found")
}
// Find the first stable version
for _, v := range versions {
if v.Stable {
// Remove the "go" prefix from the version
return strings.TrimPrefix(v.Version, "go"), nil
}
}
// If no stable version is found, return the first version
return strings.TrimPrefix(versions[0].Version, "go"), nil
}
func downloadFileWithProgress(url, filepath string) error {
// Send HEAD request to get the file size
headResp, err := http.Head(url)
if err != nil {
return err
}
defer headResp.Body.Close()
if headResp.StatusCode != http.StatusOK {
return fmt.Errorf("bad status: %s (URL: %s)", headResp.Status, url)
}
totalBytes := headResp.ContentLength
// Now send the actual GET request
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("bad status: %s (URL: %s)", resp.Status, url)
}
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
// Create a progress reader
progressR := newProgressReader(resp.Body, totalBytes)
// Copy the data using the progress reader
_, err = io.Copy(out, progressR)
// Ensure the progress bar shows 100% when download is complete
fmt.Print(renderProgressBar(100))
return err
}
func downloadFile(url, filepath string) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("bad status: %s (URL: %s)", resp.Status, url)
}
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
return err
}
func untargz(src, dst string) error {
file, err := os.Open(src)
if err != nil {
return err
}
defer file.Close()
gzr, err := gzip.NewReader(file)
if err != nil {
return err
}
defer gzr.Close()
tr := tar.NewReader(gzr)
for {
header, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return err
}
path := filepath.Join(dst, header.Name)
switch header.Typeflag {
case tar.TypeDir:
if err := os.MkdirAll(path, 0755); err != nil {
return err
}
case tar.TypeReg:
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
outFile, err := os.Create(path)
if err != nil {
return err
}
if _, err := io.Copy(outFile, tr); err != nil {
outFile.Close()
return err
}
outFile.Close()
if err := os.Chmod(path, os.FileMode(header.Mode)); err != nil {
return err
}
}
}
return nil
}
func unzip(src, dst string) error {
r, err := zip.OpenReader(src)
if err != nil {
return err
}
defer r.Close()
for _, f := range r.File {
path := filepath.Join(dst, f.Name)
if f.FileInfo().IsDir() {
os.MkdirAll(path, f.Mode())
continue
}
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return err
}
outFile, err := os.OpenFile(path, 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
}
// copyDir recursively copies a directory tree from src to dst.
func copyDir(src, dst string) error {
return filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
rel, err := filepath.Rel(src, path)
if err != nil {
return err
}
target := filepath.Join(dst, rel)
if info.IsDir() {
return os.MkdirAll(target, info.Mode())
}
return copyFile(path, target, info.Mode())
})
}
// copyFile copies a single file from src to dst with the given permissions.
func copyFile(src, dst string, mode os.FileMode) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, in)
return err
}
// expandPath expands a path with ~ and converts it to an absolute path
func expandPath(path string) (string, error) {
// Expand ~ in the path
if path == "~" || strings.HasPrefix(path, "~/") {
usr, err := user.Current()
if err != nil {
return "", fmt.Errorf("error getting current user: %v", err)
}
if path == "~" {
path = usr.HomeDir
} else {
path = filepath.Join(usr.HomeDir, path[2:])
}
}
// Convert to absolute path if it's not already
if !filepath.IsAbs(path) {
absPath, err := filepath.Abs(path)
if err != nil {
return "", fmt.Errorf("error resolving absolute path: %v", err)
}
path = absPath
}
return path, nil
}
// isUnattendedMode checks if unattended mode is enabled
func isUnattendedMode(unattendedFlag, uFlag *bool) bool {
return *unattendedFlag || *uFlag
}
// isHelpRequested checks if help was requested
func isHelpRequested(helpFlag, hFlag *bool) bool {
return *helpFlag || *hFlag
}
// getCustomGOPATH returns the custom GOPATH from flags if provided
func getCustomGOPATH(gopathFlag, gopathShortFlag *string) string {
customPath := *gopathFlag
if customPath == "" {
customPath = *gopathShortFlag
}
return customPath
}
// expandPathOrExit expands a path and exits on error
func expandPathOrExit(path string) string {
expandedPath, err := expandPath(path)
if err != nil {
color.Red("%v", err)
os.Exit(1)
}
return expandedPath
}
// setupEnvrcIfRequested sets up a .envrc file if the envrcFlag is provided
func setupEnvrcIfRequested(envrcFlag *string, goroot, gopath string) {
if *envrcFlag != "" {
err := setupEnvrcFile(*envrcFlag, goroot, gopath)
if err != nil {
color.Red("Error setting up .envrc file: %v", err)
} else {
color.Yellow("Run 'direnv allow' to enable the environment variables")
}
}
}
// setupEnvrcFile creates or updates a .envrc file with Go environment variables
func setupEnvrcFile(envrcPath, goroot, gopath string) error {
// Expand the path if needed
expandedPath, err := expandPath(envrcPath)
if err != nil {
return fmt.Errorf("error expanding envrc path: %v", err)
}
// If the path is a directory, append .envrc to it
fileInfo, err := os.Stat(expandedPath)
if err == nil && fileInfo.IsDir() {
expandedPath = filepath.Join(expandedPath, ".envrc")
}
// Create the directory if it doesn't exist
err = os.MkdirAll(filepath.Dir(expandedPath), 0755)
if err != nil {
return fmt.Errorf("error creating directory for .envrc: %v", err)
}
// Check if the file already exists
fileExists := false
if _, err := os.Stat(expandedPath); err == nil {
fileExists = true
// Check if Go environment variables are already set in the file
content, err := os.ReadFile(expandedPath)
if err != nil {
return fmt.Errorf("error reading existing .envrc file: %v", err)
}
if strings.Contains(string(content), "GOROOT=") {
color.Yellow("Go environment variables already exist in %s", expandedPath)
color.Yellow("Not modifying the existing .envrc file")
return nil
}
}
// Open the file in append mode if it exists, or create it if it doesn't
var f *os.File
if fileExists {
f, err = os.OpenFile(expandedPath, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("error opening .envrc file: %v", err)
}
// Add a newline before our content if the file doesn't end with one
content, err := os.ReadFile(expandedPath)
if err != nil {
f.Close()
return fmt.Errorf("error reading .envrc file: %v", err)
}
if len(content) > 0 && !strings.HasSuffix(string(content), "\n") {
_, err = f.WriteString("\n")
if err != nil {
f.Close()
return fmt.Errorf("error writing to .envrc file: %v", err)
}
}
} else {
f, err = os.OpenFile(expandedPath, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("error creating .envrc file: %v", err)
}
}
defer f.Close()
// Write the environment variables
_, err = f.WriteString("\n# Go environment variables added by getgo\n")
if err != nil {
return fmt.Errorf("error writing to .envrc file: %v", err)
}
// Write the exports based on the OS
if runtime.GOOS == "windows" {
_, err = fmt.Fprintf(f, "export GOROOT=\"%s\"\n", goroot)
if err != nil {
return fmt.Errorf("error writing to .envrc file: %v", err)
}
_, err = fmt.Fprintf(f, "export GOPATH=\"%s\"\n", gopath)
if err != nil {
return fmt.Errorf("error writing to .envrc file: %v", err)
}
_, err = fmt.Fprintf(f, "export PATH=\"$GOPATH/bin:$GOROOT/bin:$PATH\"\n")
if err != nil {
return fmt.Errorf("error writing to .envrc file: %v", err)
}
} else {
_, err = fmt.Fprintf(f, "export GOROOT=%s\n", goroot)
if err != nil {
return fmt.Errorf("error writing to .envrc file: %v", err)
}
_, err = fmt.Fprintf(f, "export GOPATH=%s\n", gopath)
if err != nil {
return fmt.Errorf("error writing to .envrc file: %v", err)
}
_, err = fmt.Fprintf(f, "export PATH=$GOPATH/bin:$GOROOT/bin:$PATH\n")
if err != nil {
return fmt.Errorf("error writing to .envrc file: %v", err)
}
}
if fileExists {
color.Green("Appended Go environment variables to existing .envrc file at %s", expandedPath)
} else {
color.Green("Created new .envrc file with Go environment variables at %s", expandedPath)
}
return nil
}