Skip to content

Commit

Permalink
run: new command
Browse files Browse the repository at this point in the history
  • Loading branch information
ekalinin committed Jul 21, 2020
1 parent 39ace94 commit 75e68ee
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 9 deletions.
64 changes: 64 additions & 0 deletions cmd/run.go
Original file line number Diff line number Diff line change
@@ -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 <command>",
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")
}
26 changes: 17 additions & 9 deletions utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -313,26 +313,34 @@ 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
}

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()
Expand Down

0 comments on commit 75e68ee

Please sign in to comment.