forked from bwhaley/ssmsh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssmsh.go
87 lines (77 loc) · 1.79 KB
/
ssmsh.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
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/abiosoft/ishell"
"github.com/bwhaley/ssmsh/commands"
"github.com/bwhaley/ssmsh/parameterstore"
"github.com/mattn/go-shellwords"
)
var Version string
func main() {
var version bool
_fn := flag.String("file", "", "Read commands from file (use - for stdin)")
flag.BoolVar(&version, "version", false, "Display the current version")
flag.Parse()
if version {
fmt.Println("Version", Version)
os.Exit(0)
}
shell := ishell.New()
var ps parameterstore.ParameterStore
err := ps.NewParameterStore()
if err != nil {
shell.Println("Error initializing session. Is your authentication correct?", err)
os.Exit(1)
}
commands.Init(shell, &ps)
fn := *_fn
if fn == "-" {
processStdin(shell, fn)
} else if fn != "" {
processFile(shell, fn)
} else if len(flag.Args()) > 1 {
shell.Process(flag.Args()...)
} else {
shell.Run()
}
shell.Close()
}
func processStdin(shell *ishell.Shell, fn string) {
data, err := ioutil.ReadAll(os.Stdin)
if err != nil {
shell.Println("Error reading from stdin:", err)
os.Exit(1)
}
processData(shell, string(data))
}
func processFile(shell *ishell.Shell, fn string) {
data, err := ioutil.ReadFile(fn)
if err != nil {
shell.Println("Error reading from file:", err)
}
processData(shell, string(data))
}
func processData(shell *ishell.Shell, data string) {
lines := strings.Split(data, "\n")
for _, line := range lines {
if line == "" || string(line[0]) == "#" {
continue
}
args, err := shellwords.Parse(line)
if err != nil {
msg := fmt.Errorf("Error parsing %s: %v", line, err)
shell.Println(msg)
os.Exit(1)
}
err = shell.Process(args...)
if err != nil {
msg := fmt.Errorf("Error executing %s: %v", line, err)
shell.Println(msg)
os.Exit(1)
}
}
}