diff --git a/cmd/run.go b/cmd/run.go new file mode 100644 index 0000000..c73917b --- /dev/null +++ b/cmd/run.go @@ -0,0 +1,64 @@ +package cmd + +import ( + "errors" + "os/exec" + "strings" + + "github.com/ekalinin/pbvm/utils" + "github.com/spf13/cobra" +) + +var version string + +// runCmd represents the run command +var runCmd = &cobra.Command{ + Use: "run ", + Args: cobra.ExactArgs(1), + Short: "Run a command under a version", + Long: `Run a command under a version`, + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + if len(version) < 5 { + return errors.New("Version is incorrect: " + version) + } + + installed, _, err := utils.IsInstalledVersion(pbName, version) + if err != nil { + return err + } + if !installed { + return errors.New("Version is not installed: " + version) + } + + originVersion, err := utils.GetActiveVersion(pbName) + if err != nil { + return err + } + + // TODO: run command without affecting other sessions + // (change PATH & syscall.Exec?) + + if err := utils.ActivateVersion(pbName, version); err != nil { + return err + } + defer utils.ActivateVersion(pbName, originVersion) + + cs := strings.Split(args[0], " ") + command := exec.Command(cs[0], cs[1:]...) + out, err := command.CombinedOutput() + if err != nil { + return err + } + println(string(out)) + return nil + }, +} + +func init() { + rootCmd.AddCommand(runCmd) + + runCmd.Flags().StringVar(&version, "version", "v", + "Version used for command execution") +} diff --git a/utils/utils.go b/utils/utils.go index 3f78716..68a48b0 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -313,19 +313,11 @@ func ActivateVersion(app, version string) error { // IsActiveVersion returns bool if version is active func IsActiveVersion(app, version string) (bool, error) { - activeDir, err := GetHomeActiveDir(app) - if err != nil { - return false, err - } - - l, err := os.Readlink(path.Join(activeDir, "bin")) + activeVer, err := GetActiveVersion(app) if err != nil { return false, err } - // converting - // "/home/user/.pbvm/versions/v3.12.3/bin" -> "v3.12.3" - activeVer := path.Base(path.Dir(l)) if activeVer == version { return true, nil } @@ -333,6 +325,22 @@ func IsActiveVersion(app, version string) (bool, error) { return false, nil } +// GetActiveVersion returns active version +func GetActiveVersion(app string) (string, error) { + activeDir, err := GetHomeActiveDir(app) + if err != nil { + return "", err + } + + l, err := os.Readlink(path.Join(activeDir, "bin")) + if err != nil { + return "", err + } + // converting + // "/home/user/.pbvm/versions/v3.12.3/bin" -> "v3.12.3" + return path.Base(path.Dir(l)), nil +} + // FilterAsset finds an asset which is need to be downloaded func FilterAsset(release *github.RepositoryRelease) *github.ReleaseAsset { arch := GetArch()