You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
starainrt/shell.go

163 lines
3.0 KiB
Go

package starainrt
import (
"bufio"
"fmt"
"io"
"os"
"os/exec"
"runtime"
"strings"
"syscall"
"time"
)
type suncli struct {
outfile io.ReadCloser
infile io.WriteCloser
errfile io.ReadCloser
cmd *exec.Cmd
thread bool
counter int
}
func (this suncli) IsExit() bool {
return ShellExit
}
func NewPipeShell(command string, arg ...string) (*suncli, error) {
var err error
lovecli := suncli{}
lovecli.counter = 0
cmd := exec.Command(command, arg...)
lovecli.cmd = cmd
lovecli.infile, err = lovecli.cmd.StdinPipe()
if err != nil {
return &lovecli, err
}
lovecli.outfile, err = lovecli.cmd.StdoutPipe()
if err != nil {
return &lovecli, err
}
lovecli.errfile, err = lovecli.cmd.StderrPipe()
if err != nil {
return &lovecli, err
}
if err := lovecli.cmd.Start(); err != nil {
return &lovecli, err
}
go func() {
lovecli.cmd.Wait()
}()
ShellExit = false
lovecli.thread = false
return &lovecli, nil
}
func (this suncli) GetResult(maxtime int) (string, string, bool) {
var stop bool
reader := bufio.NewReader(this.outfile)
erreader := bufio.NewReader(this.errfile)
if !this.thread {
this.thread = true
go func() {
var line2 string
var stack bool = false
stop = false
for {
if !stack {
go func() {
stack = true
if erreader.Size() > 0 {
line2, _ = erreader.ReadString('\n')
ShellErr += line2
line2 = ""
}
stack = false
}()
}
line, err2 := reader.ReadString('\n')
if err2 != nil || io.EOF == err2 {
stop = true
break
}
this.counter++
ShellRes += line
}
}()
}
waittm := 0
for !stop {
time.Sleep(time.Millisecond * 250)
waittm += 1
if maxtime >= 0 {
if waittm/4 > maxtime {
restr := ShellRes
ShellRes = ""
errstr := ShellErr
ShellErr = ""
return restr, errstr, false
}
}
}
ShellExit = true
this.thread = false
restr := ShellRes
ShellRes = ""
errstr := ShellErr
ShellErr = ""
return restr, errstr, true
}
func (this suncli) Exec(cmdstr string, maxtime int) (string, string, bool) {
this.infile.Write([]byte(cmdstr + "\n"))
return this.GetResult(maxtime)
}
func (this suncli) WriteCmd(cmdstr string) {
this.infile.Write([]byte(cmdstr + "\n"))
return
}
func (this suncli) ExitCode() int {
return this.cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus()
}
func MsgBox(text, defaults string) string {
var input string
input = defaults
fmt.Print(text)
fmt.Scanln(&input)
return strings.TrimSpace(input)
}
func MessageBox(text, defaults string) string {
fmt.Print(text)
inputReader := bufio.NewReader(os.Stdin)
str, _ := inputReader.ReadString('\n')
if runtime.GOOS == "windows" {
str = str[0 : len(str)-2]
} else {
str = str[0 : len(str)-1]
}
if str == "" {
str = defaults
}
return strings.TrimSpace(str)
}
func YesNo(text string, defaults bool) bool {
res := strings.ToUpper(MsgBox(text, ""))
if res == "" {
return defaults
}
res = res[0:1]
if res == "Y" {
return true
} else if res == "N" {
return false
} else {
return defaults
}
}