forked from stefaanc/golang-exec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runner.go
102 lines (84 loc) · 2.36 KB
/
runner.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
//
// Copyright (c) 2019 Stefaan Coussement
// MIT License
//
// more info: https://github.com/elebertus/golang-exec
//
package runner
import (
"fmt"
"io"
"reflect"
"strings"
"github.com/elebertus/golang-exec/runner/local"
"github.com/elebertus/golang-exec/runner/ssh"
"github.com/elebertus/golang-exec/script"
)
//------------------------------------------------------------------------------
type Error interface {
Script() *script.Script
Command() string
ExitCode() int // -1 when runner error without completing script
Error() string
Unwrap() error
}
type Runner interface {
SetStdoutWriter(io.Writer)
SetStderrWriter(io.Writer)
StdoutPipe() (io.Reader, error) // use in combination with Start() & Wait(), don't use in combination with Run()
StderrPipe() (io.Reader, error) // use in combination with Start() & Wait(), don't use in combination with Run()
Run() error
Start() error
Wait() error
Close() error
ExitCode() int // -1 when runner error without completing script
}
//------------------------------------------------------------------------------
func Run(connection interface{}, s *script.Script, arguments interface{}, stdout, stderr io.Writer) error {
if s.Error != nil {
return s.Error
}
r, err := New(connection, s, arguments)
if err != nil {
return err
}
defer r.Close()
if stdout != nil {
r.SetStdoutWriter(stdout)
}
if stderr != nil {
r.SetStderrWriter(stderr)
}
err = r.Run()
if err != nil {
return err
}
return nil
}
func New(connection interface{}, s *script.Script, arguments interface{}) (Runner, error) {
if s.Error != nil {
return nil, s.Error
}
var cType string
v := reflect.Indirect(reflect.ValueOf(connection))
if v.Kind() == reflect.Struct {
cType = strings.ToLower(v.FieldByName("Type").String())
} else { // panics if not a map
iter := v.MapRange()
for iter.Next() {
if iter.Key().String() == "Type" {
cType = strings.ToLower(iter.Value().String())
break
}
}
}
switch cType {
case "local":
return local.New(connection, s, arguments)
case "ssh":
return ssh.New(connection, s, arguments)
default:
return nil, fmt.Errorf("[golang-exec/runner/New()] invalid 'Type' in 'connection' parameter")
}
}
//------------------------------------------------------------------------------