nvm.go 17.6 KB
Newer Older
C
Corey Butler 已提交
1 2 3 4 5 6 7 8 9 10
package main

import (
  "fmt"
  "os"
  "os/exec"
  "strings"
  "io/ioutil"
  "regexp"
  "bytes"
11
  "encoding/json"
12
  "strconv"
13 14 15 16 17
  "./nvm/web"
  "./nvm/arch"
  "./nvm/file"
  "./nvm/node"
//  "./ansi"
C
Corey Butler 已提交
18 19
)

20
const (
21
  NvmVersion = "1.1.0"
22 23 24
)

type Environment struct {
C
Corey Butler 已提交
25 26 27 28 29 30 31
  settings        string
  root            string
  symlink         string
  arch            string
  proxy           string
  originalpath    string
  originalversion string
32 33 34
}

var env = &Environment{
35
  settings: os.Getenv("NVM_HOME")+"\\settings.txt",
36
  root: "",
C
Corey Butler 已提交
37
  symlink: os.Getenv("NVM_SYMLINK"),
38
  arch: os.Getenv("PROCESSOR_ARCHITECTURE"),
39
  proxy: "none",
C
Corey Butler 已提交
40 41
  originalpath: "",
  originalversion: "",
42
}
C
Corey Butler 已提交
43 44 45 46

func main() {
  args := os.Args
  detail := ""
47
  procarch := arch.Validate(env.arch)
C
Corey Butler 已提交
48

49
  Setup()
C
Corey Butler 已提交
50 51

  // Capture any additional arguments
52
  if len(args) > 2 {
C
Corey Butler 已提交
53 54
    detail = strings.ToLower(args[2])
  }
55 56 57 58
  if len(args) > 3 {
    procarch = args[3]
  }
  if len(args) < 2 {
59 60 61 62
    help()
    return
  }

C
Corey Butler 已提交
63 64
  // Run the appropriate method
  switch args[1] {
65
    case "install": install(detail,procarch)
C
Corey Butler 已提交
66
    case "uninstall": uninstall(detail)
67
    case "use": use(detail,procarch)
C
Corey Butler 已提交
68
    case "list": list(detail)
69
    case "ls": list(detail)
70 71 72 73 74 75
    case "on": enable()
    case "off": disable()
    case "root":
      if len(args) == 3 {
        updateRootDir(args[2])
      } else {
76
        fmt.Println("\nCurrent Root: "+env.root)
77
      }
78 79
    case "version":
      fmt.Println(NvmVersion)
80 81
    case "v":
      fmt.Println(NvmVersion)
82
    case "arch":
83 84 85 86 87 88 89 90 91 92 93
      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
      }
94
      _, a := node.GetCurrentVersion()
95 96
      fmt.Println("System Default: "+env.arch+"-bit.")
      fmt.Println("Currently Configured: "+a+"-bit.")
97 98 99 100 101 102 103
    case "proxy":
      if detail == "" {
        fmt.Println("Current proxy: "+env.proxy)
      } else {
        env.proxy = detail
        saveSettings()
      }
C
Corey Butler 已提交
104
    case "update": update()
C
Corey Butler 已提交
105 106 107 108
    default: help()
  }
}

C
Corey Butler 已提交
109 110 111 112 113 114 115 116 117 118 119 120 121
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
//  }
}

122
func CheckVersionExceedsLatest(version string) bool{
P
Patrick Sullivan 已提交
123
    content := web.GetRemoteTextFile("http://nodejs.org/dist/latest/SHASUMS256.txt")
124 125
    re := regexp.MustCompile("node-v(.+)+msi")
    reg := regexp.MustCompile("node-v|-x.+")
126
	latest := reg.ReplaceAllString(re.FindString(content),"")
P
Patrick Sullivan 已提交
127

128
	if version <= latest {
129 130 131 132 133 134
		return false
	} else {
		return true
	}
}

135
func install(version string, cpuarch string) {
C
Corey Butler 已提交
136
  if version == "" {
C
Corey Butler 已提交
137 138
    fmt.Println("\nInvalid version.")
    fmt.Println(" ")
C
Corey Butler 已提交
139 140 141 142
    help()
    return
  }

143 144 145 146 147 148 149 150 151 152 153 154 155 156
  cpuarch = strings.ToLower(cpuarch)

  if cpuarch != "" {
    if cpuarch != "32" && cpuarch != "64" && cpuarch != "all" {
      fmt.Println("\""+cpuarch+"\" is not a valid CPU architecture. Must be 32 or 64.")
      return
    }
  } else {
    cpuarch = env.arch
  }

  if cpuarch != "all" {
    cpuarch = arch.Validate(cpuarch)
  }
157
  
P
Patrick Sullivan 已提交
158 159 160 161 162 163 164 165
  // If user specifies "latest" version, find out what version is
  if version == "latest" {
    content := web.GetRemoteTextFile("http://nodejs.org/dist/latest/SHASUMS256.txt")
    re := regexp.MustCompile("node-v(.+)+msi")
    reg := regexp.MustCompile("node-v|-x.+")
    version = reg.ReplaceAllString(re.FindString(content),"")
  }

166
  if CheckVersionExceedsLatest(version) {
167
	fmt.Println("Node.js v"+version+" is not yet released or available.")
168 169 170
	return
  }
  
171 172 173 174 175
  if cpuarch == "64" && !web.IsNode64bitAvailable(version) {
    fmt.Println("Node.js v"+version+" is only available in 32-bit.")
    return
  }

C
Corey Butler 已提交
176
  // Check to see if the version is already installed
177
  if !node.IsVersionInstalled(env.root,version,cpuarch) {
C
Corey Butler 已提交
178

179
    if !node.IsVersionAvailable(version){
180 181 182 183 184 185
      fmt.Println("Version "+version+" is not available. If you are attempting to download a \"just released\" version,")
      fmt.Println("it may not be recognized by the nvm service yet (updated hourly). If you feel this is in error and")
      fmt.Println("you know the version exists, please visit http://github.com/coreybutler/nodedistro and submit a PR.")
      return
    }

186
    // Make the output directories
187 188
    os.Mkdir(env.root+"\\v"+version,os.ModeDir)
    os.Mkdir(env.root+"\\v"+version+"\\node_modules",os.ModeDir)
189 190

    // Download node
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
    if (cpuarch == "32" || cpuarch == "all") && !node.IsVersionInstalled(env.root,version,"32") {
      success := web.GetNodeJS(env.root,version,"32");
      if !success {
        os.RemoveAll(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");
      if !success {
        os.RemoveAll(env.root+"\\v"+version+"\\node_modules")
        fmt.Println("Could not download node.js v"+version+" 64-bit executable.")
        return
      }
    }

    if file.Exists(env.root+"\\v"+version+"\\node_modules\\npm") {
      return
    }
C
Corey Butler 已提交
211

212
    // If successful, add npm
213
    npmv := getNpmVersion(version)
E
Eddie Huang 已提交
214
    success := web.GetNpm(env.root, getNpmVersion(version))
C
Corey Butler 已提交
215
    if success {
216
      fmt.Printf("Installing npm v"+npmv+"...")
217

E
Eddie Huang 已提交
218 219 220
      // new temp directory under the nvm root
      tempDir := env.root + "\\temp"

221
      // Extract npm to the temp directory
E
Eddie Huang 已提交
222
      file.Unzip(tempDir+"\\npm-v"+npmv+".zip",tempDir+"\\nvm-npm")
223

224
      // Copy the npm and npm.cmd files to the installation directory
E
Eddie Huang 已提交
225 226 227
      os.Rename(tempDir+"\\nvm-npm\\npm-"+npmv+"\\bin\\npm",env.root+"\\v"+version+"\\npm")
      os.Rename(tempDir+"\\nvm-npm\\npm-"+npmv+"\\bin\\npm.cmd",env.root+"\\v"+version+"\\npm.cmd")
      os.Rename(tempDir+"\\nvm-npm\\npm-"+npmv,env.root+"\\v"+version+"\\node_modules\\npm")
228

E
Eddie Huang 已提交
229 230 231
      // Remove the temp directory
      // may consider keep the temp files here
      os.RemoveAll(tempDir)
232

233
      fmt.Println("\n\nInstallation complete. If you want to use this version, type\n\nnvm use "+version)
234
    } else {
235 236 237
      fmt.Println("Could not download npm for node v"+version+".")
      fmt.Println("Please visit https://github.com/npm/npm/releases/tag/v"+npmv+" to download npm.")
      fmt.Println("It should be extracted to "+env.root+"\\v"+version)
C
Corey Butler 已提交
238 239
    }

240 241
    // 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.
C
Corey Butler 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259

    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
  }

  // Determine if the version exists and skip if it doesn't
260
  if node.IsVersionInstalled(env.root,version,"32") || node.IsVersionInstalled(env.root,version,"64") {
261
    fmt.Printf("Uninstalling node v"+version+"...")
262 263 264 265 266
    v, _ := node.GetCurrentVersion()
    if v == version {
      cmd := exec.Command(env.root+"\\elevate.cmd", "cmd", "/C", "rmdir", env.symlink)
      cmd.Run()
    }
267
    e := os.RemoveAll(env.root+"\\v"+version)
C
Corey Butler 已提交
268 269
    if e != nil {
      fmt.Println("Error removing node v"+version)
270 271 272
      fmt.Println("Manually remove "+env.root+"\\v"+version+".")
    } else {
      fmt.Printf(" done")
C
Corey Butler 已提交
273 274 275 276 277 278 279
    }
  } else {
    fmt.Println("node v"+version+" is not installed. Type \"nvm list\" to see what is installed.")
  }
  return
}

280 281 282 283 284 285 286 287 288 289
func use(version string, cpuarch string) {

  if version == "32" || version == "64" {
    cpuarch = version
    v, _ := node.GetCurrentVersion()
    version = v
  }

  cpuarch = arch.Validate(cpuarch)

C
Corey Butler 已提交
290
  // Make sure the version is installed. If not, warn.
291 292 293 294 295 296 297 298 299 300 301 302
  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,"64") {
        fmt.Println("\nDid you mean node v"+version+" (64-bit)?\nIf so, type \"nvm use "+version+" 64\" to use it.")
      }
    }
C
Corey Butler 已提交
303 304 305
    return
  }

306
  // Create or update the symlink
C
Corey Butler 已提交
307
  sym, _ := os.Stat(env.symlink)
308
  if sym != nil {
309
    cmd := exec.Command(env.root+"\\elevate.cmd", "cmd", "/C", "rmdir", env.symlink)
310 311 312 313 314 315 316 317 318 319 320
    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
    }
  }

321
  c := exec.Command(env.root+"\\elevate.cmd", "cmd", "/C", "mklink", "/D", env.symlink, env.root+"\\v"+version)
C
Corey Butler 已提交
322 323 324 325 326 327 328 329 330
  var out bytes.Buffer
  var stderr bytes.Buffer
  c.Stdout = &out
  c.Stderr = &stderr
  err := c.Run()
  if err != nil {
      fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
      return
  }
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

  // Use the assigned CPU architecture
  cpuarch = arch.Validate(cpuarch)
  e32 := file.Exists(env.root+"\\v"+version+"\\node32.exe")
  e64 := file.Exists(env.root+"\\v"+version+"\\node64.exe")
  used := file.Exists(env.root+"\\v"+version+"\\node.exe")
  if (e32 || e64) {
    if used {
      if e32 {
        os.Rename(env.root+"\\v"+version+"\\node.exe",env.root+"\\v"+version+"\\node64.exe")
        os.Rename(env.root+"\\v"+version+"\\node32.exe",env.root+"\\v"+version+"\\node.exe")
      } else {
        os.Rename(env.root+"\\v"+version+"\\node.exe",env.root+"\\v"+version+"\\node32.exe")
        os.Rename(env.root+"\\v"+version+"\\node64.exe",env.root+"\\v"+version+"\\node.exe")
      }
    } else if e32 || e64 {
      os.Rename(env.root+"\\v"+version+"\\node"+cpuarch+".exe",env.root+"\\v"+version+"\\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.")
  }
C
Corey Butler 已提交
365 366 367
}

func list(listtype string) {
368
  if listtype == "" {
C
Corey Butler 已提交
369
    listtype = "installed"
370 371 372 373 374 375 376
  }
  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
  }

377 378
  if listtype == "installed" {
    fmt.Println("")
379
    inuse, a := node.GetCurrentVersion()
380

381 382 383 384 385 386 387 388 389 390 391 392 393 394
    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)"
395
//            str = ansi.Color(str,"green:black")
396
        }
397
        fmt.Printf(str+"\n")
398 399
      }
    }
400
    if len(v) == 0 {
401 402
      fmt.Println("No installations recognized.")
    }
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
  } else {
    _, stable, unstable := node.GetAvailable()

    releases := 15

    fmt.Println("\nShowing the "+strconv.Itoa(releases)+" latest available releases.\n")

    fmt.Println("      STABLE   |    UNSTABLE  ")
    fmt.Println("   ---------------------------")

    for i := 0; i < releases; i++ {
      str := "v"+stable[i]
      for ii := 10-len(str); ii > 0; ii-- {
        str = " "+str
      }
      str = str+"  |  "
      str2 := "v"+unstable[i]
      for ii := 10-len(str2); ii > 0; ii-- {
        str2 = " "+str2
      }
      fmt.Println("   "+str+str2)
    }

    fmt.Println("\nFor a complete list, visit http://coreybutler.github.io/nodedistro")
C
Corey Butler 已提交
427 428 429 430
  }
}

func enable() {
431
  dir := ""
432
  files, _ := ioutil.ReadDir(env.root)
433 434
  for _, f := range files {
    if f.IsDir() {
C
Corey Butler 已提交
435
      isnode, _ := regexp.MatchString("v",f.Name())
436 437 438 439 440 441 442
      if isnode {
        dir = f.Name()
      }
    }
  }
  fmt.Println("nvm enabled")
  if dir != "" {
443
    use(strings.Trim(regexp.MustCompile("v").ReplaceAllString(dir,"")," \n\r"),env.arch)
444 445 446
  } else {
    fmt.Println("No versions of node.js found. Try installing the latest by typing nvm install latest")
  }
C
Corey Butler 已提交
447 448 449
}

func disable() {
450
  cmd := exec.Command(env.root+"\\elevate.cmd", "cmd", "/C", "rmdir", env.symlink)
451 452
  cmd.Run()
  fmt.Println("nvm disabled")
C
Corey Butler 已提交
453 454 455
}

func help() {
C
Corey Butler 已提交
456
  fmt.Println("\nRunning version "+NvmVersion+".")
C
Corey Butler 已提交
457 458
  fmt.Println("\nUsage:")
  fmt.Println(" ")
459 460 461 462
  fmt.Println("  nvm arch                     : Show if node is running in 32 or 64 bit mode.")
  fmt.Println("  nvm install <version> [arch] : The version can be a node.js version or \"latest\" for the latest stable version.")
  fmt.Println("                                 Optionally specify whether to install the 32 or 64 bit version (defaults to system arch).")
  fmt.Println("                                 Set [arch] to \"all\" to install 32 AND 64 bit versions.")
463
  fmt.Println("  nvm list [available]         : List the node.js installations. Type \"available\" at the end to see what can be installed. Aliased as ls.")
464 465
  fmt.Println("  nvm on                       : Enable node.js version management.")
  fmt.Println("  nvm off                      : Disable node.js version management.")
466
  fmt.Println("  nvm proxy [url]              : Set a proxy to use for downloads. Leave [url] blank to see the current proxy.")
467
  fmt.Println("                                 Set [url] to \"none\" to remove the proxy.")
468
  fmt.Println("  nvm uninstall <version>      : The version must be a specific version.")
C
Corey Butler 已提交
469 470
//  fmt.Println("  nvm update                   : Automatically update nvm to the latest version.")
  fmt.Println("  nvm use [version] [arch]     : Switch to use the specified version. Optionally specify 32/64bit architecture.")
471 472 473
  fmt.Println("                                 nvm use <arch> will continue using the selected version, but switch to 32/64 bit mode.")
  fmt.Println("  nvm root [path]              : Set the directory where nvm should store different versions of node.js.")
  fmt.Println("                                 If <path> is not set, the current root will be displayed.")
474
  fmt.Println("  nvm version                  : Displays the current running version of nvm for Windows. Aliased as v.")
C
Corey Butler 已提交
475
  fmt.Println(" ")
C
Corey Butler 已提交
476 477
}

478 479 480 481
// Given a node.js version, returns the associated npm version
func getNpmVersion(nodeversion string) string {

  // Get raw text
482
  text := web.GetRemoteTextFile("https://raw.githubusercontent.com/coreybutler/nodedistro/master/nodeversions.json")
483 484 485 486 487 488 489 490 491 492 493

  // Parse
  var data interface{}
  json.Unmarshal([]byte(text), &data);
  body := data.(map[string]interface{})
  all := body["all"]
  npm := all.(map[string]interface{})

  return npm[nodeversion].(string)
}

494
func updateRootDir(path string) {
495
  _, err := os.Stat(path)
496 497 498 499 500
  if err != nil {
    fmt.Println(path+" does not exist or could not be found.")
    return
  }

501 502
  env.root = path
  saveSettings()
503 504 505
  fmt.Println("\nRoot has been set to "+path)
}

506
func saveSettings() {
C
Corey Butler 已提交
507
  content := "root: "+strings.Trim(env.root," \n\r")+"\r\narch: "+strings.Trim(env.arch," \n\r")+"\r\nproxy: "+strings.Trim(env.proxy," \n\r")+"\r\noriginalpath: "+strings.Trim(env.originalpath," \n\r")+"\r\noriginalversion: "+strings.Trim(env.originalversion," \n\r")
508 509 510 511 512
  ioutil.WriteFile(env.settings, []byte(content), 0644)
}

func Setup() {
  lines, err := file.ReadLines(env.settings)
513 514 515 516 517 518 519 520
  if err != nil {
    fmt.Println("\nERROR",err)
    os.Exit(1)
  }

  // Process each line and extract the value
  for _, line := range lines {
    if strings.Contains(line,"root:") {
521
      env.root = strings.Trim(regexp.MustCompile("root:").ReplaceAllString(line,"")," \r\n")
C
Corey Butler 已提交
522 523 524 525
    } else if strings.Contains(line,"originalpath:") {
      env.originalpath = strings.Trim(regexp.MustCompile("originalpath:").ReplaceAllString(line,"")," \r\n")
    } else if strings.Contains(line,"originalversion:") {
      env.originalversion = strings.Trim(regexp.MustCompile("originalversion:").ReplaceAllString(line,"")," \r\n")
526 527
    } else if strings.Contains(line,"arch:"){
      env.arch = strings.Trim(regexp.MustCompile("arch:").ReplaceAllString(line,"")," \r\n")
528 529 530 531 532 533 534 535
    } else if strings.Contains(line,"proxy:"){
      env.proxy = strings.Trim(regexp.MustCompile("proxy:").ReplaceAllString(line,"")," \r\n")
      if env.proxy != "none" && env.proxy != "" {
        if strings.ToLower(env.proxy[0:4]) != "http" {
          env.proxy = "http://"+env.proxy
        }
        web.SetProxy(env.proxy)
      }
536 537
    }
  }
538

539 540
  env.arch = arch.Validate(env.arch)

541
  // Make sure the directories exist
C
Corey Butler 已提交
542
  _, e := os.Stat(env.root)
543
  if e != nil {
544
    fmt.Println(env.root+" could not be found or does not exist. Exiting.")
545 546
    return
  }
547
}