github.com/sagernet/sing@v0.4.0-beta.19.0.20240518125136-f67a0988a636/common/shell/shell.go (about) 1 package shell 2 3 import ( 4 "os" 5 "os/exec" 6 "strings" 7 8 E "github.com/sagernet/sing/common/exceptions" 9 ) 10 11 type Shell struct { 12 *exec.Cmd 13 } 14 15 func Exec(name string, args ...string) *Shell { 16 command := exec.Command(name, args...) 17 command.Env = os.Environ() 18 return &Shell{command} 19 } 20 21 func (s *Shell) SetDir(path string) *Shell { 22 s.Dir = path 23 return s 24 } 25 26 func (s *Shell) Attach() *Shell { 27 s.Stdin = os.Stdin 28 s.Stdout = os.Stderr 29 s.Stderr = os.Stderr 30 return s 31 } 32 33 func (s *Shell) SetEnv(env []string) *Shell { 34 s.Env = append(os.Environ(), env...) 35 return s 36 } 37 38 func (s *Shell) Wait() error { 39 return s.buildError(s.Cmd.Wait()) 40 } 41 42 func (s *Shell) Run() error { 43 return s.buildError(s.Cmd.Run()) 44 } 45 46 func (s *Shell) Read() (string, error) { 47 output, err := s.CombinedOutput() 48 return string(output), s.buildError(err) 49 } 50 51 func (s *Shell) ReadOutput() (string, error) { 52 output, err := s.Output() 53 return strings.TrimSpace(string(output)), s.buildError(err) 54 } 55 56 func (s *Shell) buildError(err error) error { 57 if err == nil { 58 return nil 59 } 60 return E.Cause(err, "execute (", s.Path, ") ", strings.Join(s.Args, " ")) 61 }