|
| 1 | +//Package cmd |
| 2 | +/* |
| 3 | +Copyright © 2024 UnreadCode <i@unreadcode.com> |
| 4 | +
|
| 5 | +*/ |
| 6 | + |
| 7 | +package cmd |
| 8 | + |
| 9 | +import ( |
| 10 | + "fmt" |
| 11 | + "github.com/spf13/cobra" |
| 12 | + "pvm/utils" |
| 13 | + "regexp" |
| 14 | +) |
| 15 | + |
| 16 | +// useCmd represents the use command |
| 17 | +var useCmd = &cobra.Command{ |
| 18 | + Use: "use", |
| 19 | + Short: "Switch to the specified PHP version", |
| 20 | + Long: `Quickly switch between different PHP versions. |
| 21 | +usage example: |
| 22 | + pvm use 8.0 |
| 23 | +`, |
| 24 | + |
| 25 | + Run: useRun, |
| 26 | +} |
| 27 | + |
| 28 | +func init() { |
| 29 | + rootCmd.AddCommand(useCmd) |
| 30 | +} |
| 31 | + |
| 32 | +func useRun(cmd *cobra.Command, args []string) { |
| 33 | + if len(args) == 0 { |
| 34 | + utils.PrintMsg("Please specify a PHP version", "Warning", 1) |
| 35 | + } |
| 36 | + version := args[0] |
| 37 | + // 是一个有效的版本号 |
| 38 | + if !regexp.MustCompile(`^\d+\.\d+$`).MatchString(version) { |
| 39 | + utils.PrintMsg("Invalid PHP version number.", "Error", 1) |
| 40 | + } |
| 41 | + // 是否已经在使用 |
| 42 | + if currentVersion := utils.GetCurrentPhpVersion(); currentVersion == version { |
| 43 | + utils.PrintMsg(fmt.Sprintf("Already using PHP v%s", version), "Info", 0) |
| 44 | + } |
| 45 | + // 是否已经安装 |
| 46 | + if !utils.IsInstalled(version) { |
| 47 | + utils.PrintMsg(fmt.Sprintf("PHP v%s is not installed.", version), "Error", 1) |
| 48 | + } |
| 49 | + // 切换到指定版本 |
| 50 | + if err := utils.SwitchToVersion(version); err != nil { |
| 51 | + utils.PrintMsg(err.Error(), "Error", 1) |
| 52 | + } |
| 53 | + utils.PrintMsg(fmt.Sprintf("Switched to PHP v%s", version), "Success", 0) |
| 54 | +} |
0 commit comments