/
mio.go
116 lines (104 loc) · 2.15 KB
/
mio.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
package mcore
import (
"bufio"
"fmt"
"os"
"strings"
"github.com/mabetle/mcore/mcon"
)
const (
// NewLine .
NewLine = byte(10)
)
// ReadLine from os.Stdio
func ReadLine() string {
r := bufio.NewReader(os.Stdin)
//result, err := r.ReadString(NewLine)
line, _, err := r.ReadLine()
if err != nil {
mcon.PrintfRed("Error:%s\n", err)
}
result := string(line)
result = strings.TrimSuffix(result, "\n")
result = strings.TrimSuffix(result, "\r")
return result
}
// ReadArgs .
func ReadArgs() []string {
s := ReadLine()
return ParseStringToArgs(s)
}
// ReadLineWithMsg .
func ReadLineWithMsg(msgs ...interface{}) string {
msg := fmt.Sprint(msgs...)
if !String(msg).IsEndWith(":") {
msg = msg + ":"
}
mcon.PrintGreen(msg)
return ReadLine()
}
// ReadNotBlankLine .
func ReadNotBlankLine() (result string) {
for {
result = ReadLine()
if String(result).IsBlank() {
mcon.PrintRed("input blank line, try again:")
} else {
break
}
}
return
}
// ReadNotBlankLineWithMsg .
func ReadNotBlankLineWithMsg(msgs ...interface{}) string {
msg := fmt.Sprint(msgs...)
if !String(msg).IsEndWith(":") {
msg = msg + ":"
}
fmt.Print(msg)
return ReadNotBlankLine()
}
// ReadInt .
func ReadInt(msg ...interface{}) int {
v := ReadLineWithMsg(msg...)
n, err := StrToInt(v)
if err != nil {
return ReadInt("Wrong int format,try again:")
}
return n
}
// ReadNotZeroInt .
func ReadNotZeroInt(msg ...interface{}) int {
v := ReadInt(msg...)
if v == 0 {
return ReadNotZeroInt("Input not zero int, try again:")
}
return v
}
// ReadBool .
func ReadBool(dft bool, msg ...interface{}) bool {
v := ReadLineWithMsg(fmt.Sprint(msg...))
if String(v).IsBlank() {
return dft
}
return String(v).ToBool()
}
// ReadSelectArray returns select array elements.
// vs should has elements
func ReadSelectArray(vs []string, msg ...interface{}) string {
for k, v := range vs {
fmt.Printf("%d:%s\n", k, v)
}
mmsg := fmt.Sprint(msg...)
if mmsg == "" {
mmsg = "Please select one"
}
s := ReadInt(mmsg)
n := len(vs)
// out of range
if s > n-1 || s < 0 {
fmt.Printf("%d out of max range, shoud from 0 to %d\n", s, n-1)
return ReadSelectArray(vs, msg...)
}
return vs[s]
}