1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
|
package main
import (
"errors"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
pwl "github.com/justjanne/powerline-go/powerline"
)
const rubyVersionFileSuffix = "/.ruby-version"
const globalVersionFileSuffix = "/.rbenv/version"
func runRbenvCommand(cmd string, args ...string) (string, error) {
command := exec.Command(cmd, args...)
out, err := command.Output()
return string(out), err
}
// check RBENV_VERSION variable
func checkEnvForRbenvVersion() (string, error) {
rbenvVersion := os.Getenv("RBENV_VERSION")
if len(rbenvVersion) <= 0 {
return "", errors.New("Not found in RBENV_VERSION")
}
return rbenvVersion, nil
}
// check existence of .ruby_version in tree until root path
func checkForRubyVersionFileInTree() (string, error) {
var (
workingDirectory string
err error
)
workingDirectory, err = os.Getwd()
if err == nil {
for workingDirectory != "/" {
rubyVersion, rubyVersionErr := ioutil.ReadFile(workingDirectory + rubyVersionFileSuffix)
if rubyVersionErr == nil {
return strings.TrimSpace(string(rubyVersion)), nil
}
workingDirectory = filepath.Dir(workingDirectory)
}
}
return "", errors.New("No .ruby_version file found in tree")
}
// check for global version
func checkForGlobalVersion() (string, error) {
homeDir, _ := os.UserHomeDir()
globalRubyVersion, err := ioutil.ReadFile(homeDir + globalVersionFileSuffix)
if err != nil {
return "", errors.New("No global version file found in tree")
}
return strings.TrimSpace(string(globalRubyVersion)), nil
}
// retrieve rbenv version output
func checkForRbenvOutput() (string, error) {
// spawn rbenv and print out version
out, err := runRbenvCommand("rbenv", "version")
if err != nil {
return "", errors.New("Not found in rbenv output")
}
items := strings.Split(out, " ")
if len(items) <= 0 {
return "", errors.New("Not found in rbenv output")
}
return items[0], nil
}
func segmentRbenv(p *powerline) []pwl.Segment {
var (
segment string
err error
)
segment, err = checkEnvForRbenvVersion()
if err != nil {
segment, err = checkForRubyVersionFileInTree()
}
if err != nil {
segment, err = checkForGlobalVersion()
}
if err != nil {
segment, err = checkForRbenvOutput()
}
if err != nil {
return []pwl.Segment{}
}
return []pwl.Segment{{
Name: "rbenv",
Content: segment,
Foreground: p.theme.TimeFg,
Background: p.theme.TimeBg,
}}
}
|