-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
nvm.go
1530 lines (1335 loc) · 44.9 KB
/
nvm.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
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
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"log"
"net/url"
"os"
"os/exec"
"os/user"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"unsafe"
"nvm/arch"
"nvm/encoding"
"nvm/file"
"nvm/node"
"nvm/web"
"github.com/blang/semver"
// "github.com/fatih/color"
"github.com/coreybutler/go-where"
"github.com/olekukonko/tablewriter"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
)
const (
NvmVersion = "1.1.11"
)
type Environment struct {
settings string
root string
symlink string
arch string
node_mirror string
npm_mirror string
proxy string
originalpath string
originalversion string
verifyssl bool
}
var home = filepath.Clean(os.Getenv("NVM_HOME") + "\\settings.txt")
var symlink = filepath.Clean(os.Getenv("NVM_SYMLINK"))
var env = &Environment{
settings: home,
root: "",
symlink: symlink,
arch: os.Getenv("PROCESSOR_ARCHITECTURE"),
node_mirror: "",
npm_mirror: "",
proxy: "none",
originalpath: "",
originalversion: "",
verifyssl: true,
}
func main() {
args := os.Args
detail := ""
procarch := arch.Validate(env.arch)
if !isTerminal() {
alert("NVM for Windows should be run from a terminal such as CMD or PowerShell.", "Terminal Only")
os.Exit(0)
}
// Capture any additional arguments
if len(args) > 2 {
detail = args[2]
}
if len(args) > 3 {
if args[3] == "32" || args[3] == "64" {
procarch = args[3]
}
}
if len(args) < 2 {
help()
return
}
if args[1] != "version" && args[1] != "--version" && args[1] != "v" && args[1] != "-v" && args[1] != "--v" {
setup()
}
// Run the appropriate method
switch args[1] {
case "install":
install(detail, procarch)
case "uninstall":
uninstall(detail)
case "use":
use(detail, procarch)
case "list":
list(detail)
case "ls":
list(detail)
case "on":
enable()
case "off":
disable()
case "root":
if len(args) == 3 {
updateRootDir(args[2])
} else {
fmt.Println("\nCurrent Root: " + env.root)
}
case "v":
fmt.Println(NvmVersion)
case "--version":
fallthrough
case "--v":
fallthrough
case "-v":
fallthrough
case "version":
fmt.Println(NvmVersion)
case "arch":
if strings.Trim(detail, " \r\n") != "" {
detail = strings.Trim(detail, " \r\n")
if detail != "32" && detail != "64" {
fmt.Println("\"" + detail + "\" is an invalid architecture. Use 32 or 64.")
return
}
env.arch = detail
saveSettings()
fmt.Println("Default architecture set to " + detail + "-bit.")
return
}
_, a := node.GetCurrentVersion()
fmt.Println("System Default: " + env.arch + "-bit.")
fmt.Println("Currently Configured: " + a + "-bit.")
case "proxy":
if detail == "" {
fmt.Println("Current proxy: " + env.proxy)
} else {
env.proxy = detail
saveSettings()
}
case "current":
inuse, _ := node.GetCurrentVersion()
v, _ := semver.Make(inuse)
err := v.Validate()
if err != nil {
fmt.Println(inuse)
} else if inuse == "Unknown" {
fmt.Println("No current version. Run 'nvm use x.x.x' to set a version.")
} else {
fmt.Println("v" + inuse)
}
//case "update": update()
case "node_mirror":
setNodeMirror(detail)
case "npm_mirror":
setNpmMirror(detail)
case "debug":
checkLocalEnvironment()
default:
help()
}
}
// ===============================================================
// BEGIN | CLI functions
// ===============================================================
func setNodeMirror(uri string) {
env.node_mirror = uri
saveSettings()
}
func setNpmMirror(uri string) {
env.npm_mirror = uri
saveSettings()
}
func isTerminal() bool {
fileInfo, err := os.Stdout.Stat()
if err != nil {
return false
}
return (fileInfo.Mode() & os.ModeCharDevice) != 0
}
// const (
// MB_YESNOCANCEL = 0x00000003
// MB_ICONINFORMATION = 0x00000040
// IDYES = 6
// IDNO = 7
// IDCANCEL = 2
// )
// func openTerminal(msg string, caption ...string) {
// title := "Alert"
// if len(caption) > 0 {
// title = caption[0]
// }
// labels := []string{"Open CMD", "Open PowerShell", "Close"}
// var buttons []*uint16
// for _, label := range labels {
// buttons = append(buttons, syscall.StringToUTF16Ptr(label))
// }
// buttons = append(buttons, nil)
// user32 := windows.NewLazySystemDLL("user32.dll")
// mbox := user32.NewProc("MessageBoxW")
// ret, _, _ := mbox.Call(
// uintptr(0),
// uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(msg))),
// uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(title))),
// MB_YESNOCANCEL|MB_ICONINFORMATION,
// uintptr(0),
// uintptr(unsafe.Pointer(&buttons[0])),
// )
// getActiveWindow := user32.NewProc("GetActiveWindow")
// activeWindow, _, _ := getActiveWindow.Call()
// hwnd := windows.Handle(activeWindow)
// // Command to open the program or file
// switch ret {
// case IDYES:
// cmd := exec.Command("cmd", "/C", "start", "cmd", "/K", "echo Run \"nvm\" for help...")
// err := cmd.Start()
// if err != nil {
// log.Fatal(err)
// }
// case IDNO:
// cmd := exec.Command("cmd", "/C", "start", "powershell", "/K", "echo Run \"nvm\" for help...")
// err := cmd.Start()
// if err != nil {
// log.Fatal(err)
// }
// case IDCANCEL:
// fmt.Println("User clicked 'Custom Cancel'")
// // Handle 'Custom Cancel' button click here
// default:
// fmt.Println("User closed the message box")
// // Handle message box close event here
// }
// postMessage := user32.NewProc("PostMessageW")
// wmClose := 0x0010
// _, _, _ = postMessage.Call(
// uintptr(hwnd),
// uintptr(wmClose),
// 0,
// 0,
// )
// }
func alert(msg string, caption ...string) {
user32 := windows.NewLazySystemDLL("user32.dll")
mbox := user32.NewProc("MessageBoxW")
getForegroundWindow := user32.NewProc("GetForegroundWindow")
var hwnd uintptr
ret, _, _ := getForegroundWindow.Call()
if ret != 0 {
hwnd = ret
}
title := "Alert"
if len(caption) > 0 {
title = caption[0]
}
mbox.Call(hwnd, uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(msg))), uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(title))), uintptr(windows.MB_OK))
}
/*
func update() {
cmd := exec.Command("cmd", "/d", "echo", "testing")
var output bytes.Buffer
var _stderr bytes.Buffer
cmd.Stdout = &output
cmd.Stderr = &_stderr
perr := cmd.Run()
if perr != nil {
fmt.Println(fmt.Sprint(perr) + ": " + _stderr.String())
return
}
}
*/
func getVersion(version string, cpuarch string, localInstallsOnly ...bool) (string, string, error) {
requestedVersion := version
cpuarch = strings.ToLower(cpuarch)
if cpuarch != "" {
if cpuarch != "32" && cpuarch != "64" && cpuarch != "all" {
return version, cpuarch, errors.New("\"" + cpuarch + "\" is not a valid CPU architecture. Must be 32 or 64.")
}
} else {
cpuarch = env.arch
}
if cpuarch != "all" {
cpuarch = arch.Validate(cpuarch)
}
if version == "" {
return "", cpuarch, errors.New("A version argument is required but missing.")
}
// If user specifies "latest" version, find out what version is
if version == "latest" || version == "node" {
version = getLatest()
fmt.Println(version)
}
if version == "lts" {
version = getLTS()
}
if version == "newest" {
installed := node.GetInstalled(env.root)
if len(installed) == 0 {
return version, "", errors.New("No versions of node.js found. Try installing the latest by typing nvm install latest.")
}
version = installed[0]
}
if version == "32" || version == "64" {
cpuarch = version
v, _ := node.GetCurrentVersion()
version = v
}
version = versionNumberFrom(version)
v, err := semver.Make(version)
if err == nil {
err = v.Validate()
}
if err == nil {
// if the user specifies only the major/minor version, identify the latest
// version applicable to what was provided.
sv := strings.Split(version, ".")
if len(sv) < 3 {
version = findLatestSubVersion(version)
} else {
version = cleanVersion(version)
}
version = versionNumberFrom(version)
} else if strings.Contains(err.Error(), "No Major.Minor.Patch") {
latestLocalInstall := false
if len(localInstallsOnly) > 0 {
latestLocalInstall = localInstallsOnly[0]
}
version = findLatestSubVersion(version, latestLocalInstall)
if len(version) == 0 {
err = errors.New("Unrecognized version: \"" + requestedVersion + "\"")
}
}
return version, cpuarch, err
}
func install(version string, cpuarch string) {
requestedVersion := version
args := os.Args
lastarg := args[len(args)-1]
if lastarg == "--insecure" {
env.verifyssl = false
}
if strings.HasPrefix(version, "--") {
fmt.Println("\"--\" prefixes are unnecessary in NVM for Windows!")
version = strings.ReplaceAll(version, "-", "")
fmt.Printf("attempting to install \"%v\" instead...\n\n", version)
time.Sleep(2 * time.Second)
}
v, a, err := getVersion(version, cpuarch)
version = v
cpuarch = a
if err != nil {
if strings.Contains(err.Error(), "No Major.Minor.Patch") {
sv, sverr := semver.Make(version)
if sverr == nil {
sverr = sv.Validate()
}
if sverr != nil {
version = findLatestSubVersion(version)
if len(version) == 0 {
sverr = errors.New("Unrecognized version: \"" + requestedVersion + "\"")
}
}
err = sverr
}
if err != nil {
fmt.Println(err.Error())
if version == "" {
fmt.Println(" ")
help()
}
return
}
}
if err != nil {
fmt.Println("\"" + requestedVersion + "\" is not a valid version.")
fmt.Println("Please use a valid semantic version number, \"lts\", or \"latest\".")
return
}
if checkVersionExceedsLatest(version) {
fmt.Println("Node.js v" + version + " is not yet released or is not available.")
return
}
if cpuarch == "64" && !web.IsNode64bitAvailable(version) {
fmt.Println("Node.js v" + version + " is only available in 32-bit.")
return
}
// Check to see if the version is already installed
if !node.IsVersionInstalled(env.root, version, cpuarch) {
if !node.IsVersionAvailable(version) {
url := web.GetFullNodeUrl("index.json")
fmt.Println("\nVersion " + version + " is not available.\n\nThe complete list of available versions can be found at " + url)
return
}
// Make the output directories
os.Mkdir(filepath.Join(env.root, "v"+version), os.ModeDir)
os.Mkdir(filepath.Join(env.root, "v"+version, "node_modules"), os.ModeDir)
// Warn the user if they're attempting to install without verifying the remote SSL cert
if !env.verifyssl {
fmt.Println("\nWARNING: The remote SSL certificate will not be validated during the download process.\n")
}
// Download node
append32 := node.IsVersionInstalled(env.root, version, "64")
append64 := node.IsVersionInstalled(env.root, version, "32")
if (cpuarch == "32" || cpuarch == "all") && !node.IsVersionInstalled(env.root, version, "32") {
success := web.GetNodeJS(env.root, version, "32", append32)
if !success {
os.RemoveAll(filepath.Join(env.root, "v"+version, "node_modules"))
fmt.Println("Could not download node.js v" + version + " 32-bit executable.")
return
}
}
if (cpuarch == "64" || cpuarch == "all") && !node.IsVersionInstalled(env.root, version, "64") {
success := web.GetNodeJS(env.root, version, "64", append64)
if !success {
os.RemoveAll(filepath.Join(env.root, "v"+version, "node_modules"))
fmt.Println("Could not download node.js v" + version + " 64-bit executable.")
return
}
}
if file.Exists(filepath.Join(env.root, "v"+version, "node_modules", "npm")) {
npmv := getNpmVersion(version)
fmt.Println("npm v" + npmv + " installed successfully.")
fmt.Println("\n\nInstallation complete. If you want to use this version, type\n\nnvm use " + version)
return
}
// If successful, add npm
npmv := getNpmVersion(version)
success := web.GetNpm(env.root, getNpmVersion(version))
if success {
fmt.Printf("Installing npm v" + npmv + "...")
// new temp directory under the nvm root
tempDir := filepath.Join(env.root, "temp")
// Extract npm to the temp directory
err := file.Unzip(filepath.Join(tempDir, "npm-v"+npmv+".zip"), filepath.Join(tempDir, "nvm-npm"))
// Copy the npm and npm.cmd files to the installation directory
tempNpmBin := filepath.Join(tempDir, "nvm-npm", "cli-"+npmv, "bin")
// Support npm < 6.2.0
if file.Exists(tempNpmBin) == false {
tempNpmBin = filepath.Join(tempDir, "nvm-npm", "npm-"+npmv, "bin")
}
if file.Exists(tempNpmBin) == false {
log.Fatal("Failed to extract npm. Could not find " + tempNpmBin)
}
// Standard npm support
os.Rename(filepath.Join(tempNpmBin, "npm"), filepath.Join(env.root, "v"+version, "npm"))
os.Rename(filepath.Join(tempNpmBin, "npm.cmd"), filepath.Join(env.root, "v"+version, "npm.cmd"))
// npx support
if _, err := os.Stat(filepath.Join(tempNpmBin, "npx")); err == nil {
os.Rename(filepath.Join(tempNpmBin, "npx"), filepath.Join(env.root, "v"+version, "npx"))
os.Rename(filepath.Join(tempNpmBin, "npx.cmd"), filepath.Join(env.root, "v"+version, "npx.cmd"))
}
npmSourcePath := filepath.Join(tempDir, "nvm-npm", "npm-"+npmv)
if file.Exists(npmSourcePath) == false {
npmSourcePath = filepath.Join(tempDir, "nvm-npm", "cli-"+npmv)
}
moveNpmErr := os.Rename(npmSourcePath, filepath.Join(env.root, "v"+version, "node_modules", "npm"))
if moveNpmErr != nil {
// sometimes Windows can take some time to enable access to large amounts of files after unzip, use exponential backoff to wait until it is ready
for _, i := range [5]int{1, 2, 4, 8, 16} {
time.Sleep(time.Duration(i) * time.Second)
moveNpmErr = os.Rename(npmSourcePath, filepath.Join(env.root, "v"+version, "node_modules", "npm"))
if moveNpmErr == nil {
break
}
}
}
if err == nil && moveNpmErr == nil {
// Remove the temp directory
// may consider keep the temp files here
os.RemoveAll(tempDir)
fmt.Println("\n\nInstallation complete. If you want to use this version, type\n\nnvm use " + version)
} else if moveNpmErr != nil {
fmt.Println("Error: Unable to move directory " + npmSourcePath + " to node_modules: " + moveNpmErr.Error())
} else {
fmt.Println("Error: Unable to install NPM: " + err.Error())
}
} else {
fmt.Println("Could not download npm for node v" + version + ".")
fmt.Println("Please visit https://github.com/npm/cli/releases/tag/v" + npmv + " to download npm.")
fmt.Println("It should be extracted to " + env.root + "\\v" + version)
}
// Reset the SSL verification
env.verifyssl = true
// If this is ever shipped for Mac, it should use homebrew.
// If this ever ships on Linux, it should be on bintray so it can use yum, apt-get, etc.
return
} else {
fmt.Println("Version " + version + " is already installed.")
return
}
}
func uninstall(version string) {
// Make sure a version is specified
if len(version) == 0 {
fmt.Println("Provide the version you want to uninstall.")
help()
return
}
if strings.ToLower(version) == "latest" || strings.ToLower(version) == "node" {
version = getLatest()
} else if strings.ToLower(version) == "lts" {
version = getLTS()
} else if strings.ToLower(version) == "newest" {
installed := node.GetInstalled(env.root)
if len(installed) == 0 {
fmt.Println("No versions of node.js found. Try installing the latest by typing nvm install latest.")
return
}
version = installed[0]
}
version = cleanVersion(version)
// Determine if the version exists and skip if it doesn't
if node.IsVersionInstalled(env.root, version, "32") || node.IsVersionInstalled(env.root, version, "64") {
fmt.Printf("Uninstalling node v" + version + "...")
v, _ := node.GetCurrentVersion()
if v == version {
// _, err := runElevated(fmt.Sprintf(`"%s" cmd /C rmdir "%s"`, filepath.Join(env.root, "elevate.cmd"), filepath.Clean(env.symlink)))
_, err := elevatedRun("rmdir", filepath.Clean(env.symlink))
if err != nil {
fmt.Println(fmt.Sprint(err))
return
}
}
e := os.RemoveAll(filepath.Join(env.root, "v"+version))
if e != nil {
fmt.Println("Error removing node v" + version)
fmt.Println("Manually remove " + filepath.Join(env.root, "v"+version) + ".")
} else {
fmt.Printf(" done")
}
} else {
fmt.Println("node v" + version + " is not installed. Type \"nvm list\" to see what is installed.")
}
return
}
func versionNumberFrom(version string) string {
reg, _ := regexp.Compile("[^0-9]")
if reg.MatchString(version[:1]) {
if version[0:1] != "v" {
url := web.GetFullNodeUrl("latest-" + version + "/SHASUMS256.txt")
content := strings.Split(web.GetRemoteTextFile(url), "\n")[0]
if strings.Contains(content, "node") {
parts := strings.Split(content, "-")
if len(parts) > 1 {
if parts[1][0:1] == "v" {
return parts[1][1:]
}
}
}
fmt.Printf("\"%v\" is not a valid version or known alias.\n", version)
fmt.Println("\nAvailable aliases: latest, node (latest), lts\nNamed releases (boron, dubnium, etc) are also supported.")
os.Exit(0)
}
}
for reg.MatchString(version[:1]) {
version = version[1:]
}
return version
}
func splitVersion(version string) map[string]int {
parts := strings.Split(version, ".")
var result = make([]int, 3)
for i, item := range parts {
v, _ := strconv.Atoi(item)
result[i] = v
}
return map[string]int{
"major": result[0],
"minor": result[1],
"patch": result[2],
}
}
func findLatestSubVersion(version string, localOnly ...bool) string {
if len(localOnly) > 0 && localOnly[0] {
installed := node.GetInstalled(env.root)
result := ""
for _, v := range installed {
if strings.HasPrefix(v, "v"+version) {
if result != "" {
current, _ := semver.New(versionNumberFrom(result))
next, _ := semver.New(versionNumberFrom(v))
if current.LT(*next) {
result = v
}
} else {
result = v
}
}
}
if len(strings.TrimSpace(result)) > 0 {
return versionNumberFrom(result)
}
}
if len(strings.Split(version, ".")) == 2 {
all, _, _, _, _, _ := node.GetAvailable()
requested := splitVersion(version + ".0")
for _, v := range all {
available := splitVersion(v)
if requested["major"] == available["major"] {
if requested["minor"] == available["minor"] {
if available["patch"] > requested["patch"] {
requested["patch"] = available["patch"]
}
}
if requested["minor"] > available["minor"] {
break
}
}
if requested["major"] > available["major"] {
break
}
}
return fmt.Sprintf("%v.%v.%v", requested["major"], requested["minor"], requested["patch"])
}
url := web.GetFullNodeUrl("latest-v" + version + ".x" + "/SHASUMS256.txt")
content := web.GetRemoteTextFile(url)
re := regexp.MustCompile("node-v(.+)+msi")
reg := regexp.MustCompile("node-v|-[xa].+")
latest := reg.ReplaceAllString(re.FindString(content), "")
return latest
}
func accessDenied(err error) bool {
fmt.Println(fmt.Sprintf("%v", err))
if strings.Contains(strings.ToLower(err.Error()), "access is denied") {
fmt.Println("See https://bit.ly/nvm4w-help")
return true
}
return false
}
func use(version string, cpuarch string, reload ...bool) {
version, cpuarch, err := getVersion(version, cpuarch, true)
if err != nil {
if !strings.Contains(err.Error(), "No Major.Minor.Patch") {
fmt.Println(err.Error())
return
}
}
// Check if a change is needed
curVersion, curCpuarch := node.GetCurrentVersion()
if version == curVersion && cpuarch == curCpuarch {
fmt.Println("node v" + version + " (" + cpuarch + "-bit) is already in use.")
return
}
// Make sure the version is installed. If not, warn.
if !node.IsVersionInstalled(env.root, version, cpuarch) {
fmt.Println("node v" + version + " (" + cpuarch + "-bit) is not installed.")
if cpuarch == "32" {
if node.IsVersionInstalled(env.root, version, "64") {
fmt.Println("\nDid you mean node v" + version + " (64-bit)?\nIf so, type \"nvm use " + version + " 64\" to use it.")
}
}
if cpuarch == "64" {
if node.IsVersionInstalled(env.root, version, "32") {
fmt.Println("\nDid you mean node v" + version + " (32-bit)?\nIf so, type \"nvm use " + version + " 32\" to use it.")
}
}
return
}
// Remove symlink if it already exists
sym, _ := os.Lstat(env.symlink)
if sym != nil {
// _, err := runElevated(fmt.Sprintf(`"%s" cmd /C rmdir "%s"`, filepath.Join(env.root, "elevate.cmd"), filepath.Clean(env.symlink)))
_, err := elevatedRun("rmdir", filepath.Clean(env.symlink))
if err != nil {
if accessDenied(err) {
return
}
}
// // Return if the symlink already exists
// if ok {
// fmt.Print(err)
// return
// }
}
// Create new symlink
var ok bool
// ok, err = runElevated(fmt.Sprintf(`"%s" cmd /C mklink /D "%s" "%s"`, filepath.Join(env.root, "elevate.cmd"), filepath.Clean(env.symlink), filepath.Join(env.root, "v"+version)))
ok, err = elevatedRun("mklink", "/D", filepath.Clean(env.symlink), filepath.Join(env.root, "v"+version))
if err != nil {
if strings.Contains(err.Error(), "not have sufficient privilege") || strings.Contains(strings.ToLower(err.Error()), "access is denied") {
// cmd := exec.Command(filepath.Join(env.root, "elevate.cmd"), "cmd", "/C", "mklink", "/D", filepath.Clean(env.symlink), filepath.Join(env.root, "v"+version))
// var output bytes.Buffer
// var _stderr bytes.Buffer
// cmd.Stdout = &output
// cmd.Stderr = &_stderr
// perr := cmd.Run()
ok, err = elevatedRun("mklink", "/D", filepath.Clean(env.symlink), filepath.Join(env.root, "v"+version))
if err != nil {
ok = false
fmt.Println(fmt.Sprint(err)) // + ": " + _stderr.String())
} else {
ok = true
}
} else if strings.Contains(err.Error(), "file already exists") {
ok, err = elevatedRun("rmdir", filepath.Clean(env.symlink))
// ok, err = runElevated(fmt.Sprintf(`"%s" cmd /C rmdir "%s"`, filepath.Join(env.root, "elevate.cmd"), filepath.Clean(env.symlink)))
reloadable := true
if len(reload) > 0 {
reloadable = reload[0]
}
if err != nil {
fmt.Println(fmt.Sprint(err))
} else if reloadable {
use(version, cpuarch, false)
return
}
} else {
fmt.Print(fmt.Sprint(err))
}
}
if !ok {
return
}
// Use the assigned CPU architecture
cpuarch = arch.Validate(cpuarch)
nodepath := filepath.Join(env.root, "v"+version, "node.exe")
node32path := filepath.Join(env.root, "v"+version, "node32.exe")
node64path := filepath.Join(env.root, "v"+version, "node64.exe")
node32exists := file.Exists(node32path)
node64exists := file.Exists(node64path)
nodeexists := file.Exists(nodepath)
if node32exists && cpuarch == "32" { // user wants 32, but node.exe is 64
if nodeexists {
os.Rename(nodepath, node64path) // node.exe -> node64.exe
}
os.Rename(node32path, nodepath) // node32.exe -> node.exe
}
if node64exists && cpuarch == "64" { // user wants 64, but node.exe is 32
if nodeexists {
os.Rename(nodepath, node32path) // node.exe -> node32.exe
}
os.Rename(node64path, nodepath) // node64.exe -> node.exe
}
fmt.Println("Now using node v" + version + " (" + cpuarch + "-bit)")
}
func useArchitecture(a string) {
if strings.ContainsAny("32", os.Getenv("PROCESSOR_ARCHITECTURE")) {
fmt.Println("This computer only supports 32-bit processing.")
return
}
if a == "32" || a == "64" {
env.arch = a
saveSettings()
fmt.Println("Set to " + a + "-bit mode")
} else {
fmt.Println("Cannot set architecture to " + a + ". Must be 32 or 64 are acceptable values.")
}
}
func list(listtype string) {
if listtype == "" {
listtype = "installed"
}
if listtype != "installed" && listtype != "available" {
fmt.Println("\nInvalid list option.\n\nPlease use on of the following\n - nvm list\n - nvm list installed\n - nvm list available")
help()
return
}
if listtype == "installed" {
fmt.Println("")
inuse, a := node.GetCurrentVersion()
v := node.GetInstalled(env.root)
for i := 0; i < len(v); i++ {
version := v[i]
isnode, _ := regexp.MatchString("v", version)
str := ""
if isnode {
if "v"+inuse == version {
str = str + " * "
} else {
str = str + " "
}
str = str + regexp.MustCompile("v").ReplaceAllString(version, "")
if "v"+inuse == version {
str = str + " (Currently using " + a + "-bit executable)"
// str = ansi.Color(str,"green:black")
}
fmt.Printf(str + "\n")
}
}
if len(v) == 0 {
fmt.Println("No installations recognized.")
}
} else {
_, lts, current, stable, unstable, _ := node.GetAvailable()
releases := 20
data := make([][]string, releases, releases+5)
for i := 0; i < releases; i++ {
release := make([]string, 4, 6)
release[0] = ""
release[1] = ""
release[2] = ""
release[3] = ""
if len(current) > i {
if len(current[i]) > 0 {
release[0] = current[i]
}
}
if len(lts) > i {
if len(lts[i]) > 0 {
release[1] = lts[i]
}
}
if len(stable) > i {
if len(stable[i]) > 0 {
release[2] = stable[i]
}
}
if len(unstable) > i {
if len(unstable[i]) > 0 {
release[3] = unstable[i]
}
}
data[i] = release
}
fmt.Println("")
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{" Current ", " LTS ", " Old Stable ", "Old Unstable"})
table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false})
table.SetAlignment(tablewriter.ALIGN_CENTER)
table.SetCenterSeparator("|")
table.AppendBulk(data) // Add Bulk Data
table.Render()
fmt.Println("\nThis is a partial list. For a complete list, visit https://nodejs.org/en/download/releases")
}
}
func enable() {
dir := ""
files, _ := ioutil.ReadDir(env.root)
for _, f := range files {
if f.IsDir() {
isnode, _ := regexp.MatchString("v", f.Name())
if isnode {
dir = f.Name()
}
}
}
fmt.Println("nvm enabled")
if dir != "" {
use(strings.Trim(regexp.MustCompile("v").ReplaceAllString(dir, ""), " \n\r"), env.arch)
} else {
fmt.Println("No versions of node.js found. Try installing the latest by typing nvm install latest")
}
}
func disable() {
// ok, err := runElevated(fmt.Sprintf(`"%s" cmd /C rmdir "%s"`, filepath.Join(env.root, "elevate.cmd"), filepath.Clean(env.symlink)))
ok, err := elevatedRun("rmdir", filepath.Clean(env.symlink))
if !ok {
return
}
if err != nil {
fmt.Print(fmt.Sprint(err))
}
fmt.Println("nvm disabled")
}
const (
VER_PLATFORM_WIN32s = 0
VER_PLATFORM_WIN32_WINDOWS = 1
VER_PLATFORM_WIN32_NT = 2
)
type OSVersionInfoEx struct {
OSVersionInfoSize uint32
MajorVersion uint32
MinorVersion uint32
BuildNumber uint32
PlatformId uint32
CSDVersion [128]uint16
}
func checkLocalEnvironment() {
problems := make([]string, 0)
// Check for PATH problems
paths := strings.Split(os.Getenv("PATH"), ";")
current := env.symlink
if strings.HasSuffix(current, "/") || strings.HasSuffix(current, "\\") {
current = current[:len(current)-1]
}
nvmsymlinkfound := false
for _, path := range paths {
if strings.HasSuffix(path, "/") || strings.HasSuffix(path, "\\") {