This repository has been archived by the owner on Jun 13, 2022. It is now read-only.
forked from rgburke/grv
/
shell_command_processor.go
421 lines (355 loc) · 11.6 KB
/
shell_command_processor.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
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"os/exec"
"sync"
log "github.com/Sirupsen/logrus"
)
// ShellCommandOutputType represents a way command output can be handled
type ShellCommandOutputType int
// The set of supported command output types
const (
NoOutput ShellCommandOutputType = iota
WindowOutput
TerminalOutput
StatusBarOutput
)
var shellCommandPrefixOutputType = map[rune]ShellCommandOutputType{
'@': NoOutput,
'!': TerminalOutput,
}
// OutputType returns the ShellCommandOutputType the provided shell command prefix maps to
// or WindowOuput if no mapping exists
func OutputType(shellCommandPrefix rune) ShellCommandOutputType {
if outputType, ok := shellCommandPrefixOutputType[shellCommandPrefix]; ok {
return outputType
}
return WindowOutput
}
type referenceType int
const (
rtNone referenceType = iota
rtVariable
rtPrompt
)
// ShellCommandProcessor processes a shell command before executing it
type ShellCommandProcessor struct {
channels Channels
variables GRVVariableGetter
command []rune
outputType ShellCommandOutputType
refs []referenceOccurence
lock sync.Mutex
}
type referencePosition struct {
startIndex int
endIndex int
}
type variableReference struct {
pos *referencePosition
variable GRVVariable
}
func (ref *variableReference) position() *referencePosition {
return ref.pos
}
type promptReference struct {
pos *referencePosition
prompt string
value string
}
func (ref *promptReference) position() *referencePosition {
return ref.pos
}
type referenceOccurence interface {
position() *referencePosition
}
// NewShellCommandProcessor creates a new instance
func NewShellCommandProcessor(channels Channels, variables GRVVariableGetter, command string, outputType ShellCommandOutputType) *ShellCommandProcessor {
return &ShellCommandProcessor{
channels: channels,
variables: variables,
command: []rune(command),
outputType: outputType,
}
}
// Execute performs variable expansion on the command
// and then executes the command using the configured
// output type
func (processor *ShellCommandProcessor) Execute() {
processor.lock.Lock()
go func() {
defer processor.lock.Unlock()
log.Debugf("Processing command: %v", string(processor.command))
processor.findReferences()
processor.determinePromptValues()
command := processor.replaceReferences()
log.Debugf("Executing command: %v", command)
processor.executeCommand(command)
}()
}
func (processor *ShellCommandProcessor) findReferences() {
for position := 0; position < len(processor.command); position++ {
refType, candidate := processor.nextReferenceCandidate(position)
if refType == rtNone || candidate == nil {
break
} else if refType == rtVariable {
if variable := processor.getVariable(candidate); variable != nil {
log.Debugf("Found variable %v at %v", GRVVariableName(variable.variable), *candidate)
processor.refs = append(processor.refs, variable)
position = variable.pos.endIndex
}
} else if refType == rtPrompt {
promptRef := processor.getPrompt(candidate)
log.Debugf("Found prompt %v at %v", promptRef.prompt, *candidate)
processor.refs = append(processor.refs, promptRef)
position = promptRef.pos.endIndex
}
}
}
func (processor *ShellCommandProcessor) nextReferenceCandidate(processorIndex int) (referenceType, *referencePosition) {
var startIndex int
for i := processorIndex; i+1 < len(processor.command); i++ {
if (processor.command[i] == '$' || processor.command[i] == '?') && processor.command[i+1] == '{' {
startIndex = i
break
}
}
var endIndex int
for i := startIndex + 1; i < len(processor.command); i++ {
if processor.command[i] == '}' {
endIndex = i
break
}
}
if endIndex > startIndex {
refType := rtVariable
if processor.command[startIndex] == '?' {
refType = rtPrompt
}
return refType, &referencePosition{
startIndex: startIndex,
endIndex: endIndex,
}
}
return rtNone, nil
}
func (processor *ShellCommandProcessor) getVariable(variableCandidate *referencePosition) *variableReference {
variableName := string(processor.command[variableCandidate.startIndex+2 : variableCandidate.endIndex])
if variable, exists := LookupGRVVariable(variableName); exists {
return &variableReference{
variable: variable,
pos: variableCandidate,
}
}
return nil
}
func (processor *ShellCommandProcessor) getPrompt(position *referencePosition) *promptReference {
prompt := string(processor.command[position.startIndex+2 : position.endIndex])
return &promptReference{
prompt: prompt,
pos: position,
}
}
func (processor *ShellCommandProcessor) determinePromptValues() {
if len(processor.refs) == 0 {
return
}
var waitGroup sync.WaitGroup
for _, ref := range processor.refs {
promptRef, isPromptRef := ref.(*promptReference)
if !isPromptRef {
continue
}
waitGroup.Add(1)
processor.channels.DoAction(Action{ActionType: ActionCustomPrompt, Args: []interface{}{
ActionCustomPromptArgs{
prompt: promptRef.prompt,
inputHandler: func(input string) {
promptRef.value = input
waitGroup.Done()
},
},
}})
}
waitGroup.Wait()
}
func (processor *ShellCommandProcessor) replaceReferences() (processedCommand string) {
if len(processor.refs) == 0 {
return string(processor.command)
}
var buf bytes.Buffer
index := 0
for _, ref := range processor.refs {
for ; index < ref.position().startIndex; index++ {
buf.WriteRune(processor.command[index])
}
var value string
if variableRef, isVariableRef := ref.(*variableReference); isVariableRef {
value, _ = processor.variables.VariableValue(variableRef.variable)
} else if promptRef, isPromptRef := ref.(*promptReference); isPromptRef {
value = promptRef.value
}
buf.WriteString(value)
index = ref.position().endIndex + 1
}
for ; index < len(processor.command); index++ {
buf.WriteRune(processor.command[index])
}
return buf.String()
}
func (processor *ShellCommandProcessor) executeCommand(command string) {
switch processor.outputType {
case NoOutput:
processor.runNoOutputCommand(command)
case WindowOutput:
processor.runWindowOutputCommand(command)
case TerminalOutput:
processor.runTerminalOutputCommand(command)
case StatusBarOutput:
panic("StatusBarOutput shell command not implemented")
default:
panic("Invalid shell command output type")
}
}
func (processor *ShellCommandProcessor) runTerminalOutputCommand(command string) {
processor.channels.DoAction(Action{ActionType: ActionRunCommand, Args: []interface{}{
ActionRunCommandArgs{
command: command,
interactive: true,
promptForInput: true,
stdin: os.Stdin,
stdout: os.Stdout,
stderr: os.Stderr,
onComplete: func(commandErr error, exitStatus int) (err error) {
if commandErr != nil {
return fmt.Errorf(`Command "%v" failed: %v"`, command, commandErr)
} else if exitStatus != 0 {
return fmt.Errorf(`Command "%v" exited with status %v`, command, exitStatus)
}
processor.channels.ReportStatus(`Command "%v" exited with status %v`, command, exitStatus)
return
},
},
}})
}
func (processor *ShellCommandProcessor) runWindowOutputCommand(command string) {
processor.channels.DoAction(Action{ActionType: ActionCreateCommandOutputView, Args: []interface{}{
ActionCreateCommandOutputViewArgs{
command: command,
viewDimension: ViewDimension{
cols: 80,
rows: 24,
},
onCreation: func(commandOutputProcessor CommandOutputProcessor) {
processor.runNonInteractiveCommand(command, commandOutputProcessor)
},
},
}})
}
func (processor *ShellCommandProcessor) runNonInteractiveCommand(command string, commandOutputProcessor CommandOutputProcessor) {
var scanner *bufio.Scanner
processor.channels.DoAction(Action{ActionType: ActionRunCommand, Args: []interface{}{
ActionRunCommandArgs{
command: command,
interactive: false,
beforeStart: func(cmd *exec.Cmd) {
stdout, err := cmd.StdoutPipe()
if err != nil {
commandOutputProcessor.OnCommandExecutionError(err)
return
}
stderr, err := cmd.StderrPipe()
if err != nil {
commandOutputProcessor.OnCommandExecutionError(err)
return
}
scanner = bufio.NewScanner(io.MultiReader(stdout, stderr))
},
onStart: func(cmd *exec.Cmd) {
for scanner.Scan() {
commandOutputProcessor.AddOutputLine(scanner.Text())
}
},
onComplete: func(commandErr error, exitStatus int) (err error) {
if commandErr != nil {
commandOutputProcessor.OnCommandExecutionError(commandErr)
} else {
commandOutputProcessor.OnCommandComplete(exitStatus)
}
return
},
},
}})
}
func (processor *ShellCommandProcessor) runNoOutputCommand(command string) {
processor.channels.DoAction(Action{ActionType: ActionRunCommand, Args: []interface{}{
ActionRunCommandArgs{
command: command,
onComplete: func(commandErr error, exitStatus int) (err error) {
if commandErr != nil {
return fmt.Errorf(`Command "%v" failed: %v"`, command, commandErr)
} else if exitStatus != 0 {
return fmt.Errorf(`Command "%v" exited with status %v`, command, exitStatus)
}
return
},
},
}})
}
// GenerateShellCommandHelpSections generates help information for shell commands
func GenerateShellCommandHelpSections(config Config) (helpSections []*HelpSection) {
description := []HelpSectionText{
{text: "Shell commands can be specified by using the following prefixes: ! or @."},
{text: "The ! prefix runs the command and displays the output in a pop-up window."},
{text: "The @ prefix runs the command silently and does not display any output."},
{text: "For example, to run the command 'git pull' and see the output in a window:"},
{},
{text: ":!git pull", themeComponentID: CmpHelpViewSectionCodeBlock},
{},
{text: "Alternatively to run the command 'git pull' without seeing the output:"},
{},
{text: ":@git pull", themeComponentID: CmpHelpViewSectionCodeBlock},
{},
{text: "Key sequences can be mapped to shell commands."},
{text: "For example, to map 'gp' to run the command 'git pull' in the background:"},
{},
{text: ":map All gp @git pull", themeComponentID: CmpHelpViewSectionCodeBlock},
{},
{text: "GRV maintains a set of variables that can be embedded in shell commands."},
{text: "These variables represent the current state of the visible views."},
{text: "The set of variables available is:"},
}
helpSections = append(helpSections, &HelpSection{
title: HelpSectionText{text: "Shell Commands"},
description: description,
})
helpSections = append(helpSections, GenerateGRVVariablesHelpSection(config))
helpSections = append(helpSections, &HelpSection{
description: []HelpSectionText{
{text: "Variables can be specified in shell commands using the syntax:"},
{},
{text: "${variable}", themeComponentID: CmpHelpViewSectionCodeBlock},
{},
{text: "For example, to cherry-pick the currently selected commit:"},
{},
{text: ":!git cherry-pick ${commit}", themeComponentID: CmpHelpViewSectionCodeBlock},
{},
{text: "User input can also be specified in shell commands by specifying a custom prompt."},
{text: "The syntax for a custom prompt is:"},
{},
{text: "?{prompt text}", themeComponentID: CmpHelpViewSectionCodeBlock},
{},
{text: "For example, to create a new branch from the currently selected commit:"},
{},
{text: ":!git branch ?{New Branch Name: } ${commit}", themeComponentID: CmpHelpViewSectionCodeBlock},
{},
{text: "When the above command is run the user will be shown the prompt: 'New Branch Name: '"},
{text: "The value entered into the prompt will be substituted into the command when executed."},
},
})
return
}