-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsh.go
More file actions
277 lines (251 loc) · 8.75 KB
/
sh.go
File metadata and controls
277 lines (251 loc) · 8.75 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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package command
//go:generate go run ./internal/generate/sh -p lesiw.io/fs -t FS -f
//go:generate go run ./internal/generate/sh -p lesiw.io/command -t Machine
import (
"context"
"fmt"
"sync"
"lesiw.io/fs"
"lesiw.io/zeros"
)
// Sh is a Machine that routes commands to different machines based on
// command name, similar to how a system shell routes commands via $PATH.
//
// Unlike a raw Machine, a Sh requires explicit registration of all
// commands. Unregistered commands return "command not found" errors.
// This creates a controlled environment with explicit command provenance.
//
// A Sh wraps a "core" machine (accessible via the Unwrapper interface)
// which is used for operations like OS detection and filesystem probing, but
// not for direct command execution unless explicitly routed.
//
// Sh provides convenient methods for common operations that delegate to
// package-level functions. This provides an ergonomic API while maintaining
// flexibility for code that needs to work with the Machine interface.
//
// Example:
//
// sh := command.Shell(sys.Machine())
// sh = sh.Handle("jq", jqMachine)
// sh = sh.Handle("go", goMachine)
//
// // Ergonomic method calls
// out, err := sh.Read(ctx, "jq", ".foo") // ✓
// data, err := sh.ReadFile(ctx, "config.yaml")
//
// // Unregistered commands fail
// sh.Read(ctx, "cat", "file") // ✗ command not found
type Sh struct {
routes zeros.Map[string, Machine]
m Machine // The underlying machine (core or self)
fallback bool // Enable fallback to inner machine
once sync.Once
// Cached values (populated on first use)
os string
arch string
fsys fs.FS
}
// Shell creates a new shell that wraps the given core machine.
// Commands must be explicitly registered via Handle to be accessible.
// The core machine is accessible via the Unwrapper interface for operations
// like OS detection and filesystem probing.
//
// Optional commands can be provided as varargs. Each specified command
// will be routed to the underlying machine via sh.Handle(cmd, sh.Unshell()).
// This is equivalent to manually calling:
//
// sh := command.Shell(core)
// for _, cmd := range commands {
// sh = sh.Handle(cmd, sh.Unshell())
// }
//
// Example:
//
// // Whitelist specific commands
// sh := command.Shell(sys.Machine(), "go", "git", "make")
// sh.Read(ctx, "go", "version") // ✓ Works
// sh.Read(ctx, "cat", "file") // ✗ command not found
//
// This follows the exec.Command naming pattern where the constructor has
// the longer name and returns a pointer to the shorter type name.
func Shell(core Machine, commands ...string) *Sh {
sh := &Sh{
m: core,
}
for _, cmd := range commands {
sh = sh.Handle(cmd, sh.Unshell())
}
return sh
}
// init detects and caches OS, Arch, and FS on first use.
// This is called once via sync.Once to ensure thread-safe initialization.
func (sh *Sh) init(ctx context.Context) {
sh.once.Do(func() {
sh.os = OS(ctx, sh.m)
sh.arch = Arch(ctx, sh.m)
})
if sh.fsys == nil {
sh.fsys = FS(sh.m)
}
}
// OS returns the operating system type for this shell.
// The value is detected only once on first use and cached for performance.
// Returns normalized GOOS values: "linux", "darwin", "freebsd", "openbsd",
// "netbsd", "dragonfly", "windows", or "unknown".
func (sh *Sh) OS(ctx context.Context) string {
sh.init(ctx)
return sh.os
}
// Arch returns the architecture for this shell.
// The value is detected only once on first use and cached for performance.
// Returns normalized GOARCH values: "amd64", "arm64", "386", "arm", or
// "unknown".
func (sh *Sh) Arch(ctx context.Context) string {
sh.init(ctx)
return sh.arch
}
// FS returns the filesystem for this shell.
// The filesystem is created only once on first use and cached for performance.
func (sh *Sh) FS() fs.FS {
if sh.fsys == nil {
sh.fsys = FS(sh.m)
}
return sh.fsys
}
// Env returns the value of the environment variable named by key.
// It probes the inner machine (sh.m) to retrieve the value, piercing through
// Shell layers just like OS() and Arch() do.
//
// This is a convenience method that calls [Env].
func (sh *Sh) Env(ctx context.Context, key string) string {
return Env(ctx, sh.m, key)
}
// Shutdown shuts down the underlying machine if it is a [ShutdownMachine].
func (sh *Sh) Shutdown(ctx context.Context) error {
return Shutdown(ctx, sh.m)
}
// Handle registers a machine to handle the specified command.
// Returns the shell for method chaining.
func (sh *Sh) Handle(command string, machine Machine) *Sh {
sh.routes.Set(command, machine)
return sh
}
// HandleFunc registers a function to handle the specified command.
// This is a convenience wrapper around Handle for function handlers.
// Returns the shell for method chaining.
func (sh *Sh) HandleFunc(
command string,
fn func(context.Context, ...string) Buffer,
) *Sh {
return sh.Handle(command, MachineFunc(fn))
}
// Command implements the Machine interface. It routes the command to the
// registered machine based on the command name (args[0]).
// If no machine is registered, behavior depends on the fallback flag:
// with fallback, falls back to inner machine; without fallback, returns error.
func (sh *Sh) Command(ctx context.Context, args ...string) Buffer {
sh.init(ctx)
return sh.command(ctx, sh.fallback, args...)
}
// Unshell implements the Unsheller interface. It returns the machine
// one layer down (the inner/core machine that was wrapped by Shell).
//
// This allows selective command whitelisting by explicitly routing
// specific commands to the underlying machine:
//
// sh := command.Shell(sys.Machine())
// sh = sh.Handle("go", sh.Unshell()) // Whitelist "go" command
//
// IMPORTANT: This breaks Shell's portability guarantees. The returned
// machine will execute commands on the underlying machine even if they
// aren't explicitly registered in the Shell.
func (sh *Sh) Unshell() Machine {
return sh.m
}
// command is the shared routing logic used by both Command() and fallback.
// If fallback is true, unregistered commands fall back to the inner machine.
// If fallback is false, unregistered commands return NotFoundError.
func (sh *Sh) command(
ctx context.Context, fallback bool, args ...string,
) Buffer {
if len(args) == 0 {
return Fail(fmt.Errorf("no command specified"))
}
cmdName := args[0]
// Try registered route
if machine, ok := sh.routes.CheckGet(cmdName); ok {
return machine.Command(ctx, args...)
}
// No route found
if fallback {
return sh.m.Command(ctx, args...)
}
return Fail(&Error{
Err: fmt.Errorf("command not found: %s", cmdName),
})
}
// MachineFunc is an adapter to allow ordinary functions to be used as
// Machines. This is similar to http.HandlerFunc.
type MachineFunc func(context.Context, ...string) Buffer
// Command implements the Machine interface.
func (f MachineFunc) Command(ctx context.Context, args ...string) Buffer {
return f(ctx, args...)
}
// Handle registers a handler for a specific command name on the given machine.
// If m is already a Sh, the handler is added to it.
// Otherwise, a new Sh is created with m as the core machine, with fallback
// enabled to preserve visibility of the underlying machine's commands.
//
// This allows users to work with Machine as their primary interface while
// building up a shell:
//
// m := sys.Machine()
// m = command.Handle(m, "jq", jqMachine)
// m = command.Handle(m, "go", goMachine)
// // m is now routing with fallback to sys.Machine() commands
//
// The handled command takes precedence, but unhandled commands still work:
//
// m := sys.Machine()
// m = command.Handle(m, "echo", customEchoMachine)
// m.Command(ctx, "echo", "hello") // Uses customEchoMachine
// m.Command(ctx, "cat", "file") // Falls back to sys.Machine()
//
// For more ergonomic usage, consider using Sh methods directly:
//
// sh := command.Shell(sys.Machine())
// sh.Handle("jq", jqMachine).Handle("go", goMachine)
func Handle(m Machine, command string, handler Machine) Machine {
if sh, ok := m.(*Sh); ok {
sh.Handle(command, handler)
return sh
}
sh := Shell(m)
sh.fallback = true // Enable fallback for non-Sh machines
sh.Handle(command, handler)
return sh
}
// HandleFunc is a convenience wrapper around Handle for function handlers.
// This matches the pattern of http.HandleFunc.
//
// m := sys.Machine()
// m = command.HandleFunc(m, "echo",
// func(ctx context.Context, args ...string) Buffer {
// // Custom echo implementation
// return customMachine.Command(ctx, args...)
// })
//
// For more ergonomic usage, consider using Sh methods directly:
//
// sh := command.Shell(sys.Machine())
// sh.HandleFunc("echo",
// func(ctx context.Context, args ...string) Buffer {
// return customMachine.Command(ctx, args...)
// })
func HandleFunc(
m Machine,
command string,
fn func(context.Context, ...string) Buffer,
) Machine {
return Handle(m, command, MachineFunc(fn))
}