FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
shfmt/interp/handler.go at master · patrickvane/shfmt · GitHub
patrickvane
shfmt
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
shfmt
/
interp
/
handler.go
Copy path
More file actions
More file actions
Latest commit
History
History
History
291 lines (267 loc) · 7.66 KB
Breadcrumbs
shfmt
/
interp
/
handler.go
Copy path
File metadata and controls
291 lines (267 loc) · 7.66 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
// Copyright (c) 2017, Daniel Martí <mvdan@mvdan.cc>
// See LICENSE for licensing information
package
interp
import
(
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"syscall"
"time"
"mvdan.cc/sh/v3/expand"
)
// HandlerCtx returns HandlerContext value stored in ctx.
// It panics if ctx has no HandlerContext stored.
func
HandlerCtx
(
ctx
context.
Context
)
HandlerContext
{
hc
,
ok
:=
ctx
.
Value
(
handlerCtxKey
{}).(
HandlerContext
)
if
!
ok
{
panic
(
"interp.HandlerCtx: no HandlerContext in ctx"
)
}
return
hc
}
type
handlerCtxKey
struct
{}
// HandlerContext is the data passed to all the handler functions via a context value.
// It contains some of the current state of the Runner.
type
HandlerContext
struct
{
// Env is a read-only version of the interpreter's environment,
// including environment variables, global variables, and local function
// variables.
Env
expand.
Environ
// Dir is the interpreter's current directory.
Dir
string
// Stdin is the interpreter's current standard input reader.
Stdin
io.
Reader
// Stdout is the interpreter's current standard output writer.
Stdout
io.
Writer
// Stderr is the interpreter's current standard error writer.
Stderr
io.
Writer
}
// ExecHandlerFunc is a handler which executes simple command. It is
// called for all CallExpr nodes where the first argument is neither a
// declared function nor a builtin.
//
// Returning nil error sets commands exit status to 0. Other exit statuses
// can be set with NewExitStatus. Any other error will halt an interpreter.
type
ExecHandlerFunc
func
(
ctx
context.
Context
,
args
[]
string
)
error
// DefaultExecHandler returns an ExecHandlerFunc used by default.
// It finds binaries in PATH and executes them.
// When context is cancelled, interrupt signal is sent to running processes.
// KillTimeout is a duration to wait before sending kill signal.
// A negative value means that a kill signal will be sent immediately.
// On Windows, the kill signal is always sent immediately,
// because Go doesn't currently support sending Interrupt on Windows.
// Runner.New sets killTimeout to 2 seconds by default.
func
DefaultExecHandler
(
killTimeout
time.
Duration
)
ExecHandlerFunc
{
return
func
(
ctx
context.
Context
,
args
[]
string
)
error
{
hc
:=
HandlerCtx
(
ctx
)
path
,
err
:=
LookPath
(
hc
.
Env
,
args
[
0
])
if
err
!=
nil
{
fmt
.
Fprintln
(
hc
.
Stderr
,
err
)
return
NewExitStatus
(
127
)
}
cmd
:=
exec.
Cmd
{
Path
:
path
,
Args
:
args
,
Env
:
execEnv
(
hc
.
Env
),
Dir
:
hc
.
Dir
,
Stdin
:
hc
.
Stdin
,
Stdout
:
hc
.
Stdout
,
Stderr
:
hc
.
Stderr
,
}
err
=
cmd
.
Start
()
if
err
==
nil
{
if
done
:=
ctx
.
Done
();
done
!=
nil
{
go
func
() {
<-
done
if
killTimeout
<=
0
||
runtime
.
GOOS
==
"windows"
{
_
=
cmd
.
Process
.
Signal
(
os
.
Kill
)
return
}
// TODO: don't temporarily leak this goroutine
// if the program stops itself with the
// interrupt.
go
func
() {
time
.
Sleep
(
killTimeout
)
_
=
cmd
.
Process
.
Signal
(
os
.
Kill
)
}()
_
=
cmd
.
Process
.
Signal
(
os
.
Interrupt
)
}()
}
err
=
cmd
.
Wait
()
}
switch
x
:=
err
.(
type
) {
case
*
exec.
ExitError
:
// started, but errored - default to 1 if OS
// doesn't have exit statuses
if
status
,
ok
:=
x
.
Sys
().(syscall.
WaitStatus
);
ok
{
if
status
.
Signaled
() {
if
ctx
.
Err
()
!=
nil
{
return
ctx
.
Err
()
}
return
NewExitStatus
(
uint8
(
128
+
status
.
Signal
()))
}
return
NewExitStatus
(
uint8
(
status
.
ExitStatus
()))
}
return
NewExitStatus
(
1
)
case
*
exec.
Error
:
// did not start
fmt
.
Fprintf
(
hc
.
Stderr
,
"%v
\n
"
,
err
)
return
NewExitStatus
(
127
)
default
:
return
err
}
}
}
func
checkStat
(
dir
,
file
string
) (
string
,
error
) {
if
!
filepath
.
IsAbs
(
file
) {
file
=
filepath
.
Join
(
dir
,
file
)
}
info
,
err
:=
os
.
Stat
(
file
)
if
err
!=
nil
{
return
""
,
err
}
m
:=
info
.
Mode
()
if
m
.
IsDir
() {
return
""
,
fmt
.
Errorf
(
"is a directory"
)
}
if
runtime
.
GOOS
!=
"windows"
&&
m
&
0o111
==
0
{
return
""
,
fmt
.
Errorf
(
"permission denied"
)
}
return
file
,
nil
}
func
winHasExt
(
file
string
)
bool
{
i
:=
strings
.
LastIndex
(
file
,
"."
)
if
i
<
0
{
return
false
}
return
strings
.
LastIndexAny
(
file
,
`:\/`
)
<
i
}
func
findExecutable
(
dir
,
file
string
,
exts
[]
string
) (
string
,
error
) {
if
len
(
exts
)
==
0
{
// non-windows
return
checkStat
(
dir
,
file
)
}
if
winHasExt
(
file
) {
if
file
,
err
:=
checkStat
(
dir
,
file
);
err
==
nil
{
return
file
,
nil
}
}
for
_
,
e
:=
range
exts
{
f
:=
file
+
e
if
f
,
err
:=
checkStat
(
dir
,
f
);
err
==
nil
{
return
f
,
nil
}
}
return
""
,
fmt
.
Errorf
(
"not found"
)
}
func
driveLetter
(
c
byte
)
bool
{
return
(
c
>=
'a'
&&
c
<=
'z'
)
||
(
c
>=
'A'
&&
c
<=
'Z'
)
}
// splitList is like filepath.SplitList, but always using the unix path
// list separator ':'. On Windows, it also makes sure not to split
// [A-Z]:[/\].
func
splitList
(
path
string
) []
string
{
if
path
==
""
{
return
[]
string
{
""
}
}
list
:=
strings
.
Split
(
path
,
":"
)
if
runtime
.
GOOS
!=
"windows"
{
return
list
}
// join "C", "/foo" into "C:/foo"
var
fixed
[]
string
for
i
:=
0
;
i
<
len
(
list
);
i
++
{
s
:=
list
[
i
]
switch
{
case
len
(
s
)
!=
1
,
!
driveLetter
(
s
[
0
]):
case
i
+
1
>=
len
(
list
):
// last element
case
strings
.
IndexAny
(
list
[
i
+
1
],
`/\`
)
!=
0
:
// next element doesn't start with / or \
default
:
fixed
=
append
(
fixed
,
s
+
":"
+
list
[
i
+
1
])
i
++
continue
}
fixed
=
append
(
fixed
,
s
)
}
return
fixed
}
// LookPath is similar to os/exec.LookPath, with the difference that it uses the
// provided environment. env is used to fetch relevant environment variables
// such as PWD and PATH.
//
// If no error is returned, the returned path must be valid.
func
LookPath
(
env
expand.
Environ
,
file
string
) (
string
,
error
) {
pathList
:=
splitList
(
env
.
Get
(
"PATH"
).
String
())
chars
:=
`/`
if
runtime
.
GOOS
==
"windows"
{
chars
=
`:\/`
// so that "foo" always tries "./foo"
pathList
=
append
([]
string
{
"."
},
pathList
...
)
}
exts
:=
pathExts
(
env
)
dir
:=
env
.
Get
(
"PWD"
).
String
()
if
strings
.
ContainsAny
(
file
,
chars
) {
return
findExecutable
(
dir
,
file
,
exts
)
}
for
_
,
elem
:=
range
pathList
{
var
path
string
switch
elem
{
case
""
,
"."
:
// otherwise "foo" won't be "./foo"
path
=
"."
+
string
(
filepath
.
Separator
)
+
file
default
:
path
=
filepath
.
Join
(
elem
,
file
)
}
if
f
,
err
:=
findExecutable
(
dir
,
path
,
exts
);
err
==
nil
{
return
f
,
nil
}
}
return
""
,
fmt
.
Errorf
(
"%q: executable file not found in $PATH"
,
file
)
}
func
pathExts
(
env
expand.
Environ
) []
string
{
if
runtime
.
GOOS
!=
"windows"
{
return
nil
}
pathext
:=
env
.
Get
(
"PATHEXT"
).
String
()
if
pathext
==
""
{
return
[]
string
{
".com"
,
".exe"
,
".bat"
,
".cmd"
}
}
var
exts
[]
string
for
_
,
e
:=
range
strings
.
Split
(
strings
.
ToLower
(
pathext
),
`;`
) {
if
e
==
""
{
continue
}
if
e
[
0
]
!=
'.'
{
e
=
"."
+
e
}
exts
=
append
(
exts
,
e
)
}
return
exts
}
// OpenHandlerFunc is a handler which opens files. It is
// called for all files that are opened directly by the shell, such as
// in redirects. Files opened by executed programs are not included.
//
// The path parameter may be relative to the current directory, which can be
// fetched via HandlerCtx.
//
// Use a return error of type *os.PathError to have the error printed to
// stderr and the exit status set to 1. If the error is of any other type, the
// interpreter will come to a stop.
type
OpenHandlerFunc
func
(
ctx
context.
Context
,
path
string
,
flag
int
,
perm
os.
FileMode
) (io.
ReadWriteCloser
,
error
)
// DefaultOpenHandler returns an OpenHandlerFunc used by default. It uses os.OpenFile to open files.
func
DefaultOpenHandler
()
OpenHandlerFunc
{
return
func
(
ctx
context.
Context
,
path
string
,
flag
int
,
perm
os.
FileMode
) (io.
ReadWriteCloser
,
error
) {
mc
:=
HandlerCtx
(
ctx
)
if
!
filepath
.
IsAbs
(
path
) {
path
=
filepath
.
Join
(
mc
.
Dir
,
path
)
}
return
os
.
OpenFile
(
path
,
flag
,
perm
)
}
}
Back
|
FazBrowse Home
|
New Git URL