|
| 1 | +package commandCli |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "path/filepath" |
| 8 | + |
| 9 | + "github.com/codegangsta/cli" |
| 10 | + "github.com/ystyle/jvms/internal/entity" |
| 11 | + "github.com/ystyle/jvms/utils/file" |
| 12 | + "github.com/ystyle/jvms/utils/jdk" |
| 13 | + "github.com/ystyle/jvms/utils/web" |
| 14 | +) |
| 15 | + |
| 16 | +func install(cfx *entity.Config) *cli.Command { |
| 17 | + cmd := &cli.Command{ |
| 18 | + Name: "install", |
| 19 | + ShortName: "i", |
| 20 | + Usage: "Install available remote jdk", |
| 21 | + Action: func(c *cli.Context) error { |
| 22 | + if cfx.Proxy != "" { |
| 23 | + web.SetProxy(cfx.Proxy) |
| 24 | + } |
| 25 | + v := c.Args().Get(0) |
| 26 | + if v == "" { |
| 27 | + return errors.New("invalid version., Type \"jvms rls\" to see what is available for install") |
| 28 | + } |
| 29 | + |
| 30 | + if jdk.IsVersionInstalled(cfx.Store, v) { |
| 31 | + fmt.Println("Version " + v + " is already installed.") |
| 32 | + return nil |
| 33 | + } |
| 34 | + versions, err := getJdkVersions(cfx) |
| 35 | + if err != nil { |
| 36 | + return err |
| 37 | + } |
| 38 | + |
| 39 | + if !file.Exists(cfx.Download) { |
| 40 | + os.MkdirAll(cfx.Download, 0777) |
| 41 | + } |
| 42 | + if !file.Exists(cfx.Store) { |
| 43 | + os.MkdirAll(cfx.Store, 0777) |
| 44 | + } |
| 45 | + |
| 46 | + for _, version := range versions { |
| 47 | + if version.Version == v { |
| 48 | + dlzipfile, success := web.GetJDK(cfx.Download, v, version.Url) |
| 49 | + if success { |
| 50 | + fmt.Printf("Installing JDK %s ...\n", v) |
| 51 | + |
| 52 | + // Extract jdk to the temp directory |
| 53 | + jdktempfile := filepath.Join(cfx.Download, fmt.Sprintf("%s_temp", v)) |
| 54 | + if file.Exists(jdktempfile) { |
| 55 | + err := os.RemoveAll(jdktempfile) |
| 56 | + if err != nil { |
| 57 | + panic(err) |
| 58 | + } |
| 59 | + } |
| 60 | + err := file.Unzip(dlzipfile, jdktempfile) |
| 61 | + if err != nil { |
| 62 | + return fmt.Errorf("unzip failed: %w", err) |
| 63 | + } |
| 64 | + |
| 65 | + // Copy the jdk files to the installation directory |
| 66 | + temJavaHome := getJavaHome(jdktempfile) |
| 67 | + err = os.Rename(temJavaHome, filepath.Join(cfx.Store, v)) |
| 68 | + if err != nil { |
| 69 | + return fmt.Errorf("unzip failed: %w", err) |
| 70 | + } |
| 71 | + |
| 72 | + // Remove the temp directory |
| 73 | + // may consider keep the temp files here |
| 74 | + os.RemoveAll(jdktempfile) |
| 75 | + |
| 76 | + fmt.Println("Installation complete. If you want to use this version, type\n\njvms switch", v) |
| 77 | + } else { |
| 78 | + fmt.Println("Could not download JDK " + v + " executable.") |
| 79 | + } |
| 80 | + return nil |
| 81 | + } |
| 82 | + } |
| 83 | + return errors.New("invalid version., Type \"jvms rls\" to see what is available for install") |
| 84 | + }, |
| 85 | + } |
| 86 | + return cmd |
| 87 | +} |
0 commit comments