-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
188 lines (166 loc) · 4.77 KB
/
main.go
File metadata and controls
188 lines (166 loc) · 4.77 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
package main
import (
"bufio"
"context"
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"plugin"
"regexp"
"strings"
"github.com/RevREB/ProjectBrix/api"
"github.com/RevREB/ProjectBrix/plugins/syscmd"
)
var (
reCmd = regexp.MustCompile(`\S+`)
)
type Goshell struct {
ctx context.Context
pluginsDir string
commands map[string]api.Command
}
func New() *Goshell {
return &Goshell{
pluginsDir: api.PluginsDir,
commands: make(map[string]api.Command),
}
}
func (gosh *Goshell) Init(ctx context.Context) error {
gosh.ctx = ctx
gosh.printSplash()
return gosh.loadCommands()
}
func (gosh *Goshell) loadCommands() error {
if _, err := os.Stat(gosh.pluginsDir); err != nil {
return err
}
plugins, err := listFiles(gosh.pluginsDir, `.*_command.so`)
if err != nil {
return err
}
for _, cmdPlugin := range plugins {
plug, err := plugin.Open(path.Join(gosh.pluginsDir, cmdPlugin.Name()))
if err != nil {
fmt.Printf("failed to open plugin %s: %v\n", cmdPlugin.Name(), err)
continue
}
cmdSymbol, err := plug.Lookup(api.CmdSymbolName)
if err != nil {
fmt.Printf("plugin %s does not export symbol \"%s\"\n",
cmdPlugin.Name(), api.CmdSymbolName)
continue
}
commands, ok := cmdSymbol.(api.Commands)
if !ok {
fmt.Printf("Symbol %s (from %s) does not implement Commands interface\n",
api.CmdSymbolName, cmdPlugin.Name())
continue
}
if err := commands.Init(gosh.ctx); err != nil {
fmt.Printf("%s initialization failed: %v\n", cmdPlugin.Name(), err)
continue
}
for name, cmd := range commands.Registry() {
gosh.commands[name] = cmd
}
gosh.ctx = context.WithValue(gosh.ctx, "gosh.commands", gosh.commands)
}
return nil
}
// TODO delegate splash to a plugin
func (gosh *Goshell) printSplash() {
fmt.Println(`
██████╗ ██████╗ ██╗██╗ ██╗ ██████╗██╗ ██╗
██╔══██╗██╔══██╗██║╚██╗██╔╝██╔════╝██║ ██║
██████╔╝██████╔╝██║ ╚███╔╝ ██║ ██║ ██║
██╔══██╗██╔══██╗██║ ██╔██╗ ██║ ██║ ██║
██████╔╝██║ ██║██║██╔╝ ██╗╚██████╗███████╗██║
╚═════╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═╝ ╚═════╝╚══════╝╚═╝
`)
}
func (gosh *Goshell) handle(ctx context.Context, cmdLine string) (context.Context, error) {
line := strings.TrimSpace(cmdLine)
if line == "" {
return ctx, nil
}
args := reCmd.FindAllString(line, -1)
if args != nil {
cmdName := args[0]
cmd, ok := gosh.commands[cmdName]
if !ok {
return ctx, errors.New(fmt.Sprintf("command not found: %s", cmdName))
}
return cmd.Exec(ctx, args)
}
return ctx, errors.New(fmt.Sprintf("unable to parse command line: %s", line))
}
func listFiles(dir, pattern string) ([]os.FileInfo, error) {
files, err := ioutil.ReadDir(dir)
if err != nil {
return nil, err
}
filteredFiles := []os.FileInfo{}
for _, file := range files {
if file.IsDir() {
continue
}
matched, err := regexp.MatchString(pattern, file.Name())
if err != nil {
return nil, err
}
if matched {
filteredFiles = append(filteredFiles, file)
}
}
return filteredFiles, nil
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ctx = context.WithValue(ctx, "gosh.prompt", api.DefaultPrompt)
ctx = context.WithValue(ctx, "gosh.stdout", os.Stdout)
ctx = context.WithValue(ctx, "gosh.stderr", os.Stderr)
ctx = context.WithValue(ctx, "gosh.stdin", os.Stdin)
shell := New()
if err := shell.Init(ctx); err != nil {
fmt.Print("\n\nfailed to initialize:", err)
os.Exit(1)
}
// prompt for help
cmdCount := len(shell.commands)
if cmdCount > 0 {
if _, ok := shell.commands["help"]; ok {
fmt.Printf("\nLoaded %d command(s)...", cmdCount)
fmt.Println("\nType help for available commands")
fmt.Print("\n")
}
} else {
fmt.Print("\n\nNo commands found")
}
// shell loop
go func(shellCtx context.Context, shell *Goshell) {
lineReader := bufio.NewReader(os.Stdin)
loopCtx := shellCtx
for {
fmt.Printf("%s ", api.GetPrompt(loopCtx))
line, err := lineReader.ReadString('\n')
if err != nil {
fmt.Println(err)
return
}
// TODO: future enhancement is to capture input key by key
// to give command granular notification of key events.
// This could be used to implement command autocompletion.
c, err := shell.handle(loopCtx, line)
loopCtx = c
if err != nil {
fmt.Printf("%v\n", err)
}
}
}(shell.ctx, shell)
// wait
// TODO: sig handling
select {}
}