-
Notifications
You must be signed in to change notification settings - Fork 24
/
helpers.go
119 lines (103 loc) 路 2.02 KB
/
helpers.go
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package utils
import (
"bufio"
"fmt"
"log"
"os"
"os/user"
"path/filepath"
"runtime"
"strconv"
"strings"
)
type sshUrl struct {
Username string
Host string
Port int
}
// ParseSSHUrl build an sshUrl object from an url string
func ParseSSHUrl(url string) *sshUrl {
parts := strings.Split(url, "@")
usr, _ := user.Current()
conf := &sshUrl{}
var host string
if len(parts) == 2 {
conf.Username = parts[0]
host = parts[1]
} else {
conf.Username = usr.Username
host = parts[0]
}
hostParts := strings.Split(host, ":")
if len(hostParts) == 2 {
port, err := strconv.Atoi(hostParts[1])
if err != nil {
log.Fatalln(err)
}
if hostParts[0] == "" {
conf.Host = "127.0.0.1"
} else {
conf.Host = hostParts[0]
}
conf.Port = port
} else {
conf.Host = host
conf.Port = 22
}
return conf
}
// ExpandUserHome resolve paths like "~/.ssh/id_rsa"
func ExpandUserHome(path string) (string, error) {
usr, err := user.Current()
if err != nil {
return "", err
}
ret := path
// supports paths like "~/.ssh/id_rsa"
if strings.HasPrefix(path, "~/") {
ret = filepath.Join(usr.HomeDir, path[2:])
}
return ret, nil
}
// GetUserDefaultShell try to get the best shell for the user
func GetUserDefaultShell(username string) string {
if runtime.GOOS == "windows" {
return "c:\\windows\\system32\\windowspowershell\\v1.0\\powershell.exe"
}
fallback := "/bin/sh"
file, err := os.Open("/etc/passwd")
if err != nil {
return fallback
}
defer file.Close()
lines := bufio.NewReader(file)
for {
line, _, err := lines.ReadLine()
if err != nil {
break
}
fs := strings.Split(string(line), ":")
if len(fs) != 7 {
continue
}
if fs[0] != username {
continue
}
shell := fs[6]
return shell
}
return fallback
}
func ByteCountSI(b int64) string {
const unit = 1000
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB",
float64(b)/float64(div), "kMGTPE"[exp])
}